Alexander Suraphel
09/04/2021, 3:11 PMvar animals: List<Animal> = ArrayList<Dog>()
where Dog
-> Animal
The following won’t compile in Java:
List<Animal> animals = new ArrayList<Dog>();
Youssef Shoaib [MOD]
09/04/2021, 3:41 PMList
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.Alexander Suraphel
09/04/2021, 4:09 PMMuhammet Emin Gündoğar
09/04/2021, 9:08 PMYoussef Shoaib [MOD]
09/04/2021, 10:46 PMval 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