How do I implement a generic mathematical function in Scala

That was one of my first questions in Stack Overflow or about Scala. The problem is that Scala maintains compatibility with Java, and that means its basic numeric types are equivalent to Java’s primitives.

The problem arises in that Java primitives are not classes, and, therefore, do not have a class hierarchy which would allow a “numeric” supertype.

To put it more plainly, Java, and, therefore, Scala, does not see any common grounds between a Double‘s + and a an Int‘s +.

The way Scala finally got around this restriction was by using Numeric, and its subclasses Fractional and Integral, in the so-called typeclass pattern. Basically, you use it like this:

def square[T](x: T)(implicit num: Numeric[T]): T = {
    import num._
    x * x
}

Or, if you do not need any of the numeric operations but the methods you call do, you can use the context bound syntax for type declaration:

def numberAndSquare[T : Numeric](x: T) = x -> square(x)

For more information, see the answers in my own question.

Leave a Comment

tech