这是一个玩具示例:
object Example {
import collection.mutable
import collection.immutable.TreeSet
val x = TreeSet(1, 5, 8, 12)
val y = mutable.Set.empty ++= x
val z = TreeSet.empty ++ y
// This gives an error: unspecified parameter
// val z = TreeSet.empty() ++ y
}
Run Code Online (Sandbox Code Playgroud)
显然TreeSet.empty,TreeSet.empty()并不是一回事.引擎盖下发生了什么?我什么时候可以安全地省略(或在这种情况下不省略)括号?
我已经将一些代码发送到控制台,然后在eval上面的代码中将其删除,然后再执行以下代码:
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
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个特殊情况,并且与您何时可以并且不能省略括号不太相关.
这是签名TreeSet.empty:
def empty[A](implicit ordering: Ordering[A]): TreeSet[A]
Run Code Online (Sandbox Code Playgroud)
它有一个隐式参数列表,需要Ordering包含所包含的类型A.当你调用时TreeSet.empty,编译器会尝试隐式找到正确的Ordering[A].
但是当您调用时TreeSet.empty(),编译器会认为您正在尝试显式提供隐式参数.除了你在列表中省略了参数,这是一个编译错误(错误的参数数量).这将是唯一的方法是你明确传递一些Ordering:TreeSet.empty(Ordering.Int).
旁注:您的上面的代码实际上并没有编译TreeSet.empty,因为它屈服于一个模糊的隐式错误Ordering.Ordering[Int]您的范围中可能存在一些您未在问题中包含的内容.最好使类型显式和使用TreeSet.empty[Int].
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |