我有一个接受Numeric[T]
对象的Scala方法:
def needNumeric[T](value: T)(implicit n: Numeric[T]) = {
// do something
}
如何从 Java 调用此方法?我想出的最好的方法是:
needNumeric(0, scala.math.Numeric.IntIsIntegral$.MODULE$);
但是代码看起来很丑,而且不是很通用。有没有更好的方法?
Java支持多态方法,那么像这样的东西怎么样:
object original {
def needNumeric[T](value: T)(implicit n: Numeric[T]) = {
// do something
}
}
object NeedNumeric {
def needNumeric(value: Int) = original.needNumeric(value)
def needNumeric(value: Long) = original.needNumeric(value)
def needNumeric(value: Float) = original.needNumeric(value)
def needNumeric(value: Double) = original.needNumeric(value)
def needNumeric(value: BigInt) = original.needNumeric(value)
...
}
import NeedNumeric._
必须枚举类型很乏味(这就是 Scala 使用类型类的原因(,但对于数值来说应该是可以的,因为没有很多数值类型。
如果这是您自己的needNumeric
方法,请注意签名可以简化为:
def needNumeric[T: Numeric](value: T) = {
丑陋问题的一个小解决方法:定义Java方便的访问,如
class Numerics {
public static final Numeric<Integer> INTEGER = Numeric.IntIsIntegral$.MODULE$;
public static final Numeric<Double> DOUBLE = Numeric.DoubleIsFractional$.MODULE$;
...
}
权衡是它允许调用任何需要Numeric
的方法而不修改它。