我有一个采用 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 - 如何从 Java 调用具有数字参数的 Scala 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52033211/