Scala 在类类型参数中使用上下文绑定
我的印象是,上下文边界只适用于方法:Scala 在类类型参数中使用上下文绑定,scala,typeclass,implicit,parametric-polymorphism,Scala,Typeclass,Implicit,Parametric Polymorphism,我的印象是,上下文边界只适用于方法: trait Target[T] class Post { def pinTo[T : Target](t:T) } 显然,上下文边界也可以用于类(也可能是特征): 现在我对如何向Post提供证据感到困惑 class Business implicit object ev extends Target[Business] // is implicit necessary here ? val p = new Post[Business] // ??
trait Target[T]
class Post {
def pinTo[T : Target](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]
的隐式值参数的快捷方式。由于trait没有构造函数值参数,因此不能将其用于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]]
}
这只是一种不同的写作方式
class Bar[A](implicit foo: Foo[A])
您可以像在任何其他正常方法调用中一样提供证据:
new Bar[Int]()(new Foo[Int] {}) // explicitly
或:
new Bar[Int]()(new Foo[Int] {}) // explicitly
implicit val iFoo = new Foo[Int] {}
new Bar[Int] // implicitly