Why are Arrays invariant, but Lists covariant?

前端 未结 4 2019
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 23:53

E.g. why does

val list:List[Any] = List[Int](1,2,3)

work, but

val arr:Array[Any] = Array[Int](1,2,3)

fail

4条回答
  •  借酒劲吻你
    2020-11-30 00:15

    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

提交回复
热议问题