Scala has a number of traits that you can use as type classes, for example Ordered
and Numeric
in the package scala.math
.
I can, f
You can reduce Miles' solution to only use 1 extra line by doing this:
Add an implicit conversion from A : Numeric
to Numeric[A]#Ops
object Ops {
implicit def numeric[A : Numeric](a: A) = implicitly[Numeric[A]].mkNumericOps(a)
}
Then bring this into scope in your method
def g[T : Numeric](a: T, b: T) = {
import Ops.numeric
a * b
}
See Scala ticket 3538 for more info.