can someone tell me why this is allowed in Kotlin ...
# getting-started
a
can someone tell me why this is allowed in Kotlin but not in Java?
var animals: List<Animal> = ArrayList<Dog>()
where
Dog
->
Animal
The following won’t compile in Java:
List<Animal> animals = new ArrayList<Dog>();
y
That's because the
List
interface in Java is actually the Kotlin equivalent of
MutableList
, as in, it includes both read and write methods, and so its type parameter is declared as invariant. Try the same Kotlin example with
MutableList
and you'll see the same exact issue.
💯 3
a
That’s it @Youssef Shoaib [MOD]. Thanks!
m
mutable means something you can change and you described it read and write methods.Why it is invariant what is the relation between having read,write methods and being invariant? @Youssef Shoaib [MOD]
y
Simply, let's assume that MutableList wasn't invariant and that it behaved exactly like List. Then, this code would compile:
Copy code
val dogs: MutableList<Dog> = ArrayList<Dog>()
val animals: MutableList<Animal> = dogs
animals.add(Cat())
for(dog in dogs){
    // Woof is a method only in the class Dog
    dog.woof()
}
This code, if MutableList behaved like List, would crash at runtime with a
ClassCastException
👍 2