How can one create a class which does math and comparisons on any numeric type in Scala?
One obvious approach:
import math.Numeric.Implicits._
class Ops[T : Numeric] {
def add(a: T, b: T) = a + b
def gt(a: T, b: T) = a > b
}
Earns me this…
Ops.scala:7: value > is not a member of type parameter T
Hmmm… we can do math with numeric types, but we can’t compare them?
So let’s also say that T is Ordered[T]…
class Ops[T <: Ordered[T] : Numeric] {
def add(a: T, b: T) = a + b
def gt(a: T, b: T) = a > b
}
That compiles. But try to use it?
new Ops[Int].gt(1, 2)
And I get…
Ops.scala:13: type arguments [Int] do not conform to class Ops's type parameter bounds [T <: Ordered[T]]
So how can I operate on some type which is both ordered and numeric?
1 Answer