How to create a class that performs mathematical comparisons for any number 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 that ...
Ops.scala:7: value > is not a member of type parameter T
Hmmm ... we can do math with number types, but we can't compare them?
So, let them 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 }
It 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 type parameter bounds [T <: Ordered[T]]
So, how can I work with any type that is both ordered and numeric?
source share