Tim*_*Tim 7 math scala numeric
如何创建一个在Scala中对任何数字类型进行数学和比较的类?
一个明显的方法:
import math.Numeric.Implicits._
class Ops[T : Numeric] {
def add(a: T, b: T) = a + b
def gt(a: T, b: T) = a > b
}
Run Code Online (Sandbox Code Playgroud)
让我知道这个......
Ops.scala:7: value > is not a member of type parameter T
Run Code Online (Sandbox Code Playgroud)
嗯......我们可以用数字类型做数学,但我们无法比较它们?
所以我们也说T是Ordered[T]......
class Ops[T <: Ordered[T] : Numeric] {
def add(a: T, b: T) = a + b
def gt(a: T, b: T) = a > b
}
Run Code Online (Sandbox Code Playgroud)
编译.但尝试使用它?
new Ops[Int].gt(1, 2)
Run Code Online (Sandbox Code Playgroud)
我明白了......
Ops.scala:13: type arguments [Int] do not conform to class Ops's type parameter bounds [T <: Ordered[T]]
Run Code Online (Sandbox Code Playgroud)
那么如何操作某些有序和数字的类型呢?
mis*_*tor 14
scala> import Ordering.Implicits._
import Ordering.Implicits._
scala> import Numeric.Implicits._
import Numeric.Implicits._
scala> class Ops[T : Numeric] {
| def add(a: T, b: T) = a + b
| def gt(a: T, b: T) = a > b
| }
defined class Ops
scala> new Ops[Int].gt(12, 34)
res302: Boolean = false
Run Code Online (Sandbox Code Playgroud)