Jea*_*let 13
不,因为上下文绑定实际上是额外隐式参数的简写.
例如:
def sort[A : Ordering](xs: Seq[A])
Run Code Online (Sandbox Code Playgroud)
是一种简写形式
def sort[A](xs: Seq[A])(implicit ordering: Ordering[A])
Run Code Online (Sandbox Code Playgroud)
这不能在类型定义中表示.
Thi*_*ong 13
您不必在类型声明中直接绑定上下文,而是必须有一个单独的值声明,表示JPP提到的隐式参数.
无论谁定义类型,还必须提供上下文绑定的证据:
trait Generic {
type U
implicit val ordering: Ordering[U] // evidence for U: Ordering
def max(u1: U, u2: U) = List(u1, u2).max
}
def concrete[T: Ordering] = new Generic {
type U = T
val ordering = implicitly[Ordering[T]]
}
assert(concrete[Int].max(1,3) == 3)
Run Code Online (Sandbox Code Playgroud)