Why are Arrays invariant, but Lists covariant?

fresskoma picture fresskoma · Jul 13, 2011 · Viewed 9.4k times · Source

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?

Answer

Op De Cirkel picture Op De Cirkel · Jul 13, 2011

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