编辑:根据原始答案重写这个问题
该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) 那么为什么List(1,2,3,4).contains("wtf")甚至编译?如果编译器拒绝这个会不会很好?
例如:
scala> val l:List[String] = List("one", "two")
l: List[String] = List(one, two)
scala> l.contains(1) //wish this didn't compile
res11: Boolean = false
Run Code Online (Sandbox Code Playgroud)
在Java中以这种方式完成事情的原因的各种解释在这里似乎并不适用,因为Map和Set确实实现了类型安全版本contains和朋友.有没有办法contains在Seq上做一个类型安全的东西,不能把它克隆成一个Set?
我刚绊倒方法的以下定义to由下式定义TraversableLike(2.10.0):
override def to[Col[_]](implicit cbf: CanBuildFrom[Nothing, A, Col[A @uV]]): Col[A @uV] = {
val b = cbf()
b.sizeHint(this)
b ++= thisCollection
b.result
}
Run Code Online (Sandbox Code Playgroud)
根据这个答案,@uV禁用差异检查。这听起来很危险。我为什么要这样做?