Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is one able to assign a list of child type to a list of its superclass type, in Kotlin?

I have read topics on Generics and Wildcards in Kotlin and also their differences compared with Java, I have tried to search online, but I couldn’t find the answer to this question nor make sure if anyone has asked it.

I’ve got the class Note and the class FavouriteNote, derived from the class Note. I’ve also got an array list with type parameter Note and an array list with type parameter FavouriteNote. I’m trying to assign List<FavouriteNote> to List<Note>, which of course won’t work in Java.

public class Main {
    public static void main(String[] args) {
        List<Note> notes = new ArrayList<Note>();
        List<FavouriteNote> favouriteNotes = new ArrayList<FavouriteNote>();

        notes = favouriteNotes; // this won't compile
    }
}


class Note {
    public final String name;

    public Note(String name) {
        this.name = name;
    }
}

class FavouriteNote extends Note {
    public FavouriteNote(String name) {
        super(name);
    }
}

In Kotlin, though, I am free to assign List<FavouriteNote> to List<Note>:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

fun main() {
    var notes = emptyList<Note>()
    val favouriteNotes = emptyList<FavouriteNote>()

    notes = favouriteNotes // compiles and runs successfully
}

open class Note(val name: String)

class FavouriteNote(name: String) : Note(name)

Why is that or what can I read to learn more about how this works in Kotlin and what is happening under the hood?

>Solution :

I believe mutability plays an important part. The java example doesn’t work because Lists are mutable, as in, you are able to add new elements to it. If it allowed the assignment and you would add a Note to notes you run into the problem that favouriteNotes would contain a non-FavouriteNote since it refers to the same list.

Kotlin’s emptyList and listOf returns non-mutable lists. It allows the assignment because you can’t add anything to notes anyway. Notice that if you change notes‘s declaration as

var notes = mutableListOf<Note>()

you will run in the same compiler error as in Java

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading