Scala operations with Numeric generics

340 Views Asked by At

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?

1

There are 1 best solutions below

0
jwvh On BEST ANSWER

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)