【发布时间】:2015-09-20 21:56:58
【问题描述】:
运行以下代码时,我得到了一些奇怪的结果:
object Example {
implicit object StringOrdering extends Ordering[String] {
def compare(o1: String, o2: String) = {
o1.length - o2.length
}
}
object StringOrdering1 extends Ordering[String] {
def compare(o1: String, o2: String) = {
o2.length - o1.length
}
}
import collection.mutable
import collection.immutable.TreeSet
val x = TreeSet(1, 5, 8, 12)
val y = mutable.Set.empty ++= x // mutable.Set[Int]
val y1 = mutable.Set.empty[Int] ++= x // mutable.Set[Int]
val z = TreeSet.empty ++ y // Set[Any]
val z1 = TreeSet.empty[Int] ++ y // TreeSet[Int]
}
为什么可变集合和不可变集合中的类型推断行为如此不同? z 部分最令人费解,为什么我们至少没有得到一个TreeSet[Any]?
【问题讨论】:
-
z行不能在 2.10 或 2.11 上编译。 -
必须有一些隐含的
Ordering在此处未显示的范围内,而不是Ordering[Int],甚至无法编译。
标签: scala type-inference