Scala:如何访问`Numeric` 类型的算术运算?

Car*_*lin 4 scala numeric implicit

class Foo[T](t: T)(implicit int: Numeric[T]) {
  val negated = -t
  val doubled = t + t
  val squared = t * t
  // ...
}
Run Code Online (Sandbox Code Playgroud)

我在这里的所有三行上都有红色波浪线。是什么赋予了?

slo*_*ouc 5

你有一个Numeric[T]for some的实例T,这就是所有的好东西。所以你只需要访问你想要的方法(例如plus):

class Foo[T](t: T)(implicit int: Numeric[T]) {

  val sum = int.plus(t, t)

}
Run Code Online (Sandbox Code Playgroud)

如果您使用上下文绑定(“T : Numeric”语法糖),则:

class Foo[T : Numeric](t: T) {

  val sum = implicitly[Numeric[T]].plus(t, t)

}
Run Code Online (Sandbox Code Playgroud)

如果您想使用诸如 的快捷操作符+,您可以简单地导入隐式实例的成员:

class Foo[T](t: T)(implicit int: Numeric[T]) {

  import int._
  val sum = t + t

}
Run Code Online (Sandbox Code Playgroud)