简体   繁体   English

如何从Java调用具有数值参数的Scala方法

[英]How to call a Scala method that has Numeric parameter from Java

I have a Scala method that takes a Numeric[T] object: 我有一个采用Numeric[T]对象的Scala方法:

def needNumeric[T](value: T)(implicit n: Numeric[T]) = {
  // do something
}

How do I call this method from Java? 如何从Java调用此方法? The best way I've come up with is this: 我想出的最好方法是:

needNumeric(0, scala.math.Numeric.IntIsIntegral$.MODULE$);

But the code looks ugly and is not very general. 但是代码看起来很丑陋,不是很通用。 Is there a better way to do it? 有更好的方法吗?

Java supports polymorphic methods, so how about something like this: 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._

It is tedious to have to enumerate the types (which is why the Scala uses a type class) but it should be OK for numerical values as there aren't very many numeric types. 必须枚举类型很繁琐(这就是Scala使用类型类的原因),但是对于数值来说应该没问题,因为没有太多的数值类型。


If this is your own needNumeric method then note that the signature can be simplfied to this: 如果这是您自己的needNumeric方法,请注意,签名可以简化为:

def needNumeric[T: Numeric](value: T) = {

A slight workaround for the ugliness issue: define Java-convenient access like 丑陋问题的一个小解决方法:定义Java方便的访问,例如

class Numerics {
    public static final Numeric<Integer> INTEGER = Numeric.IntIsIntegral$.MODULE$;

    public static final Numeric<Double> DOUBLE = Numeric.DoubleIsFractional$.MODULE$;

    ...
}

The tradeoff is that it allows calling any method requiring Numeric s without modifying it. 折衷是它允许调用任何需要Numeric的方法而无需对其进行修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM