Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Arrays invariant, but Lists covariant?

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?

like image 503
fresskoma Avatar asked Jul 13 '11 19:07

fresskoma


People also ask

Why are arrays invariant?

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.

What does it mean that arrays are covariant?

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.

Are lists covariant in Scala?

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] .

Are Java arrays invariant?

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.


1 Answers

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

like image 196
Op De Cirkel Avatar answered Nov 04 '22 19:11

Op De Cirkel