How to make code using Value [T: Numeric] more "flexible", like "unpacked" counterparts?

If I have code like 5 * 5.0 , the result is converted to the most accurate type, Double .

But this does not seem to work with code like

 case class Value[T : Numeric](value: T) { type This = Value[T] def +(m: This) = Value[T](implicitly[Numeric[T]].plus(value, m.value)) ... } implicit def numToValue[T : Numeric](v: T) = Value[T](v) 

Is there a way to do things like someIntValue + double , where someIntValue is Value[Int] and Double is Double ?

PS: Sorry for the much less perfect title. I am grateful for suggestions on the best wording ...

+6
source share
1 answer

You can do this (with great difficulty) by creating implicit statements:

 abstract class Arith[A,B,C] { def +(a: A, b: B): C def -(a: A, b: B): C def *(a: A, b: B): C def /(a: A, b: B): C } implicit object ArithIntLong extends Arith[Int,Long,Long] { def +(a: Int, b: Long) = a+b def -(a: Int, b: Long) = ab def *(a: Int, b: Long) = a*b def /(a: Int, b: Long) = a/b } ... def f[A,B,C](a: A, b: B)(implicit arith: Arith[A,B,C]) = arith.*(a,b) scala> f(5,10L) res46: Long = 50 

but you really need to do more, because you only need the numerical equivalent for A and B, and asymmetric operations must be defined in both directions. And it is not very practical to specialize, given that there are three types.

+5
source

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


All Articles