scalagenericstypesnumerics

Scala operations with Numeric generics


When I tried to do

def subtract[T: Numeric](x: T, y: T) : T = x-y

in Scala 2.12, the - is not recognized. However, this is basically equivalent to what Addition with generic type parameter in Scala suggests. What do I need to change?


Solution

  • The easiest thing to do is import Numeric.Implicits._. This adds that standard infix operators, -, *, etc., to the current implicit scope. Then everything should work as expected.

    Alternatively, you can pull down the implicit and use it directly.

    def subtract[T: Numeric](x: T, y: T) : T = implicitly[Numeric[T]].minus(x,y)