为什么阵列不变,但清单协变? [英] Why are Arrays invariant, but Lists covariant?
本文介绍了为什么阵列不变,但清单协变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如。为什么
val list:List[Any] = List[Int](1,2,3)
工作,但
val arr:Array[Any] = Array[Int](1,2,3)
失败(因为数组是不变的)。这是什么设计决定背后所期望的效果?
fails (because arrays are invariant). What is the desired effect behind this design decision?
推荐答案
由于它会违反类型安全。
如果没有,你将能够做这样的事:
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
和编译器斜面抓住它。
在另一方面,列表是不变的,所以你不能添加的东西是不是内部
On the other hand, lists are immutable, so you can't add something that is not Int
这篇关于为什么阵列不变,但清单协变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文