[英]Using a context bound in a class type parameter
我的印象是上下文邊界只適用於方法:
trait Target[T]
class Post {
def pinTo[T : Target](t:T)
}
顯然,上下文界限也可以在class
上使用(也可能是trait
):
trait Target[T]
class Post[T:Target] {
def pintTo[T](t:T)
}
現在我對如何向Post
提供證據感到困惑?
class Business
implicit object ev extends Target[Business] // is implicit necessary here ?
val p = new Post[Business] // ?? how do I provide ev ?
上下文邊界的A: Foo
表示法只是要求Foo[A]
類型的隱式值參數的快捷方式。 由於traits沒有構造函數值參數, 因此不能將其與特征一起使用:
trait Foo[A]
trait Bar[A: Foo] // "error: traits cannot have type parameters with context bounds..."
而在課堂上它是可能的:
class Bar[A: Foo] {
def foo: Foo[A] = implicitly[Foo[A]]
}
這只是一種不同的寫作方式
class Bar[A](implicit foo: Foo[A])
您提供的證據就像您在任何其他常規方法調用中所做的那樣:
new Bar[Int]()(new Foo[Int] {}) // explicitly
要么:
implicit val iFoo = new Foo[Int] {}
new Bar[Int] // implicitly
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.