Comparison with Scala numeric types?

How to create a class that performs mathematical comparisons for any number type in Scala?

One obvious approach:

import math.Numeric.Implicits._ class Ops[T : Numeric] { def add(a: T, b: T) = a + b def gt(a: T, b: T) = a > b } 

Earns me that ...

 Ops.scala:7: value > is not a member of type parameter T 

Hmmm ... we can do math with number types, but we can't compare them?

So, let them also say that T is Ordered[T] ...

 class Ops[T <: Ordered[T] : Numeric] { def add(a: T, b: T) = a + b def gt(a: T, b: T) = a > b } 

It compiles. But try to use it?

 new Ops[Int].gt(1, 2) 

And I get ...

 Ops.scala:13: type arguments [Int] do not conform to class Ops type parameter bounds [T <: Ordered[T]] 

So, how can I work with any type that is both ordered and numeric?

+6
source share
2 answers
 scala> import Ordering.Implicits._ import Ordering.Implicits._ scala> import Numeric.Implicits._ import Numeric.Implicits._ scala> class Ops[T : Numeric] { | def add(a: T, b: T) = a + b | def gt(a: T, b: T) = a > b | } defined class Ops scala> new Ops[Int].gt(12, 34) res302: Boolean = false 
+14
source

You need to import mkNumericOps and / or mkOrderingOps :

 val num = implicitly[Numeric[T]] 

or

 class Ops[T](implicit num: Numeric[T]) 

then

 import num.{mkNumericOps,mkOrderingOps} 

Now you can compare and calculate with them. Perhaps this will help you in the first part of your question.

By the way: Ordered and Numeric works like this:

 class Ops[T: Ordered: Numeric] 
+4
source

Source: https://habr.com/ru/post/901722/


All Articles