frozen
frozen

Reputation: 2144

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?

Upvotes: 2

Views: 361

Answers (1)

jwvh
jwvh

Reputation: 51271

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)

Upvotes: 3

Related Questions