如何创建一个做数学的类和 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
}
赚我这个...
Ops.scala:7: value > is not a member of type parameter T
嗯...我们可以用数字类型做数学,但我们不能比较它们?
所以我们也说
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
}
这样编译。但是尝试使用它?
new Ops[Int].gt(1, 2)
我得到...
Ops.scala:13: type arguments [Int] do not conform to class Ops's type parameter bounds [T <: Ordered[T]]
那么如何对某种既有序又数字的类型进行操作呢?
最佳答案
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
关于scala - 与 Scala 的数字类型进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8169333/