[英]Use context bound in type alias
是否可以在Scala中使用類型別名中的上下文邊界?
例如
type U = A : B
您不必在類型聲明中直接綁定上下文,而是必須有一個單獨的值聲明,表示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)
不,因為上下文綁定實際上是額外隱式參數的簡寫。
例如:
def sort[A : Ordering](xs: Seq[A])
是一種簡寫形式
def sort[A](xs: Seq[A])(implicit ordering: Ordering[A])
這不能在類型定義中表示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.