编辑:根据原始答案重写这个问题
该scala.collection.immutable.Set班是不是在它的类型参数不变性.为什么是这样?
import scala.collection.immutable._
def foo(s: Set[CharSequence]): Unit = {
println(s)
}
def bar(): Unit = {
val s: Set[String] = Set("Hello", "World");
foo(s); //DOES NOT COMPILE, regardless of whether type is declared
//explicitly in the val s declaration
}
Run Code Online (Sandbox Code Playgroud) 例如,为什么呢
val list:List[Any] = List[Int](1,2,3)
Run Code Online (Sandbox Code Playgroud)
工作,但是
val arr:Array[Any] = Array[Int](1,2,3)
Run Code Online (Sandbox Code Playgroud)
失败(因为数组是不变的).这个设计决定背后的效果是什么?