为什么数组是不变的,而列表是协变的? [英] Why are Arrays invariant, but Lists covariant?

查看:21
本文介绍了为什么数组是不变的,而列表是协变的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如为什么

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

编译器无法捕获它.

另一方面,列表是不可变的,所以你不能添加不是 Int

On the other hand, lists are immutable, so you can't add something that is not Int

这篇关于为什么数组是不变的,而列表是协变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆