I need to define a class that guarantees the basic numeric operations will be present (+
, -
, *
, ...)
def Arithmetic[T <: AnyVal](a: T, b: T) {
val x = a + b
}
AnyVal
does not define +
. Second attempt:
import Numeric.implicits._
def Arithmetic[T <% Numeric](a: T, b: T) {
val x = a + b
}
So far so good, but now I am forcing T
to be of the same type. Hence Arithmetic(double, int)
will fail. My real application is even a little more contrived:
class Arithmetic[T](A: Connector[T], B: Connector[U])(implicit n: Numeric[T]) {
val sum = new Connector({ n.plus(A.value + B.value) })
}
class Constant[T](var x: T) {
val value = new Connector({ x })
}
class Connector[T](f: => T) {
def value: T = f
override def toString = value.toString()
}
Now for the usage:
object Main extends App {
val n1 = new Constant(1)
// works
val n5 = new Constant(5)
val a = new Arithmetic( n1.value, n5.value )
// doesn't work
val n55 = new Constant(5.5)
val b = new Arithmetic( n1.value, n55.value )
}
Thoughts? Suggestions? I just need something that guarantees I am able do basic math operations inside that class...