【发布时间】:2017-11-04 02:07:09
【问题描述】:
我有类似编译好的java代码。
import org.jaitools.numeric.Range;
Range<Integer> r1 = Range.create(1, true, 4, true);
像Scala一样转换成Scala
val r1: org.jaitools.numeric.Range[Integer] = org.jaitools.numeric.Range.create(1, true, 4, true)
编译失败,因为 java 似乎适用于这种方法:
public static <T extends Number & Comparable> Range<T> create(T minValue, boolean minIncluded, T maxValue, boolean maxIncluded) {
return new Range<T>(minValue, minIncluded, maxValue, maxIncluded);
}
而 Scala 编译器会选择使用
public static <T extends Number & Comparable> Range<T> create(T value, int... inf) {
return new Range<T>(value, inf);
}
即类型参数不匹配。
两者都是同一个类中的重载方法。 如何让 Scala 编译器选择正确的方法?
编辑
val r1: org.jaitools.numeric.Range[Integer] = org.jaitools.numeric.Range.create(1, true, 4, true)
结果
overloaded method value create with alternatives:
[T <: Number with Comparable[_]](x$1: T, x$2: Int*)org.jaitools.numeric.Range[T] <and>
[T <: Number with Comparable[_]](x$1: T, x$2: Boolean, x$3: T, x$4: Boolean)org.jaitools.numeric.Range[T]
cannot be applied to (Int, Boolean, Int, Boolean)
val r1: org.jaitools.numeric.Range[Integer] = org.jaitools.numeric.Range.create(1, true, 4, true)
也许这也是convert java to scala code - change of method signatures的一个例子,java和Scala的类型系统不能很好地协同工作?
【问题讨论】:
-
我不熟悉这个特定的包,但这似乎是转换类型的问题。尝试做 Range.create(int2Int(1), true, int2Int(4), true);
-
int2Int指的是哪种方法? -
请注意,您使用的是 Range[Integer],它指的是 java.util.Integer,但是在 scala 1 和 4 中是 Int。 scala predef 包含一个函数 int2Int 来进行转换。虽然这通常会自动发生,但在某些情况下可能会失败。这可能是其中之一
-
在 scala gitter 中,有人告诉我尝试
org.jaitools.numeric.Range.create(Integer.valueOf(1), true, Integer.valueOf(4), true),即使用手动装箱。这工作正常。 -
是类似的逻辑。 MIGHT 工作(但可能不会)的另一个选项是使用 org.jaitools.numeric.Range[Int]
标签: java scala static-methods overloading