https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Alexander Suraphel

09/04/2021, 3:11 PM
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

Youssef Shoaib [MOD]

09/04/2021, 3:41 PM
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

Alexander Suraphel

09/04/2021, 4:09 PM
That’s it @Youssef Shoaib [MOD]. Thanks!
m

Muhammet Emin Gündoğar

09/04/2021, 9:08 PM
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

Youssef Shoaib [MOD]

09/04/2021, 10:46 PM
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