如何使用上下文边界重写函数?

How to Rewrite Function Using Context Bounds?

给定以下 Addable 类型-class:

scala> trait Addable[A] {
     |   def add(x: A): A
     | }
defined trait Addable

我为 Int 创建了一个实例:

scala> class AddInt(x: Int) extends Addable[Int] {
     |   override def add(y: Int) = x + y
     | }
defined class AddInt

然后,我创建了一个隐式 AddInt:

scala> implicit val addInt: AddInt = new AddInt(10)
addInt: AddInt = AddInt@1f010bf0

最后,我定义了一个泛型函数,foo:

scala> def foo[A](x: A)(implicit ev: Addable[A]): A = ev.add(x)
foo: [A](x: A)(implicit ev: Addable[A])A

现在,我可以通过 addInt:

的成功隐式解析来调用它
scala> foo(10)
res0: Int = 20

如何使用 context bound 表示法定义 foo

示例:

def foo[A : Addable]...?

只需像在您自己的示例中那样定义方法:

def foo[A : Addable](x: A) = implicitly[Addable[A]].add(x)