我正在尝试编译以下 Scala 代码:
// Something that Scala is very bad at: don't try and figure out if every type I *could* possibly use supports it,
// just let me use it until I try a type that doesn't. Or at least have AnyValue provide an abstraction for all
// Numeric Types (Interface)
trait NumericValue[T] {
def +(rhs : T, lhs : T) : T
}
implicit object ByteNumericValue extends NumericValue[Byte] {
def +(rhs : Byte, lhs : Byte) : Byte = (rhs + lhs).toByte
}
implicit object ShortNumericValue extends NumericValue[Short] {
def +(rhs : Short, lhs : Short) : Short = (rhs + lhs).toShort
}
implicit object IntNumericValue extends NumericValue[Int] {
def +(rhs : Int, lhs : Int) : Int = rhs + lhs
}
implicit object LongNumericValue extends NumericValue[Long] {
def +(rhs : Long, lhs : Long) : Long = rhs + lhs
}
implicit object BigIntNumericValue extends NumericValue[BigInt] {
def +(rhs : BigInt, lhs : BigInt) : BigInt = rhs + lhs
}
def doMath[T <: AnyVal](initializer : Long)(implicit Num : NumericValue[T]) : T = {
Num.+(initializer.asInstanceOf[T], initializer.asInstanceOf[T])
}
lazy val math = doMath[Short](0)
这里的想法是我需要一种方法来使 doMath 对任何 Integer 进行操作,从而对具有加法运算符的类型进行操作。我希望它与 BigInt 之类的大数字或 Byte 之类的非常小的数字无关。
当我尝试编译它时,我得到一个错误:
error: could not find implicit value for parameter Num: NumericValue[Short]
lazy val math = doMath[Short](0)
有任何想法吗?