如何使用Value [T:Numeric]使代码更"灵活",就像"未装箱"的对应​​物一样?

soc*_*soc 6 generics scala numbers numeric implicit

如果我有代码5 * 5.0,结果转换为最准确的类型,Double.

但这似乎不适用于代码

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)
Run Code Online (Sandbox Code Playgroud)

有没有一种方法,使之类的东西someIntValue + double的工作,在那里someIntValueValue[Int]doubleDouble

PS:对不起完美的标题感到抱歉.我很感谢有关更好措辞的建议......

Rex*_*err 5

您可以通过创建隐式运算符来执行此操作(通过大量繁忙工作):

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) = a-b
  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
Run Code Online (Sandbox Code Playgroud)

但是你真的必须做更多的事情,因为你需要A和B的Numeric等价物,并且需要双向定义非对称操作.鉴于涉及三种类型,专业化并不实际.