[英]Convert java to scala - overloaded static methods
我有类似编译的Java代码。
import org.jaitools.numeric.Range;
Range<Integer> r1 = Range.create(1, true, 4, true);
转换成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)
也许这也是将Java转换为Scala代码的情况-在Java和Scala的类型系统不能很好地协同工作的情况下更改方法签名 ?
您的问题是Int
和java.lang.Integer
是两个不同的东西。 create
期望其第一个和第三个参数与type参数具有相同的类型。 您将参数指定为Integer
但是要在1和4中传递的参数的类型为Int
。
您不能创建Range[Int]
,因为类型参数是扩展Number
和Comparable
所必需的,而Int
则不需要。 因此,您必须将Int
显式包装为Integer
val r1 = org.jaitools.numeric.Range.create(Integer.valueOf(1), true, Integer.valueOf(4), true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.