【发布时间】:2009-03-24 09:11:01
【问题描述】:
编辑:根据原始答案重写此问题
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
}
【问题讨论】:
-
值得注意的是
foo(s.toSet[CharSequence])编译得很好。toSet方法是 O(1) - 它只是包装asInstanceOf。 -
还要注意
foo(Set("Hello", "World"))在 2.10 上也可以编译,因为 Scala 似乎能够推断出正确的 Set 类型。但它不适用于隐式转换 (stackoverflow.com/questions/23274033/…)。
标签: scala set covariance scala-collections