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