E.g. why does
val list:List[Any] = List[Int](1,2,3)
work, but
val arr:Array[Any] = Array[Int](1,2,3)
fails (because arrays are invariant). What is the desired effect behind this design decision?
Arrays in Kotlin are invariant, which means that an array of a specific type cannot be assigned to an array of its parent type. It is not possible to assign Array<Integer> to Array<Any> . This provides implicit type safety and prevents possible runtime errors in the application.
Arrays in the Java language are covariant -- which means that if Integer extends Number (which it does), then not only is an Integer also a Number, but an Integer[] is also a Number[] , and you are free to pass or assign an Integer[] where a Number[] is called for.
The Scala standard library has a generic immutable sealed abstract class List[+A] class, where the type parameter A is covariant. This means that a List[Cat] is a List[Animal] .
Invariance in Java and Kotlin: The return types are both covariant and the method parameters are invariant. Arrays are where the two languages behave differently. Java arrays are covariant, while Kotlin arrays are invariant. are invariant by default in both languages.
Because it would break type-safety otherwise. If not, you would be able to do something like this:
val arr:Array[Int] = Array[Int](1,2,3) val arr2:Array[Any] = arr arr2(0) = 2.54
and the compiler can't catch it.
On the other hand, lists are immutable, so you can't add something that is not Int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With