使用绑定在类类型参数中的上下文 [英] Using a context bound in a class type parameter
问题描述
我的印象是上下文范围仅适用于方法:
I was under the impression that context bounds would work only on methods:
trait Target[T]
class Post {
def pinTo[T : Target](t:T)
}
显然上下文边界也可以在class
(可能是trait
)中使用:
apparently context bounds can be used inclass
(and presumably trait
) too:
trait Target[T]
class Post[T:Target] {
def pintTo[T](t:T)
}
现在,我对如何向Post
提供证据感到困惑?
Now I'm confused as to how the evidence can be provided to 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]
的隐式值参数的快捷方式.由于特征没有构造函数值参数,因此您不能 将其与特征一起使用:
The A: Foo
notation for context bounds is only a shortcut for asking for an implicit value parameter of type Foo[A]
. Since traits do not have constructor value parameters, you can not use this with a trait:
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]]
}
这只是一种不同的写作方式
Which is just a different way of writing
class Bar[A](implicit foo: Foo[A])
您可以像在其他任何常规方法调用中一样提供证据:
You provide the evidence like you do in any other normal method call:
new Bar[Int]()(new Foo[Int] {}) // explicitly
或者:
implicit val iFoo = new Foo[Int] {}
new Bar[Int] // implicitly
这篇关于使用绑定在类类型参数中的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!