编辑: 根据原始答案重新编写了这个问题
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
包装起来。 - john sullivanfoo(Set("Hello", "World"))
也可以编译通过,因为Scala似乎能够推断出Set的正确类型。但是它不适用于隐式转换(http://stackoverflow.com/questions/23274033/implicit-definition-working-for-seq-but-not-for-set/)。 - Lionel Parreaux