将 java 转换为 scala - 重载静态方法
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);
}
即类型参数不匹配。
两者都是同一个 class 中的重载方法。
如何让 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: T, x: Int*)org.jaitools.numeric.Range[T] <and>
[T <: Number with Comparable[_]](x: T, x: Boolean, x: T, x: 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 不能很好地协同工作?
你的问题是 Int
和 java.lang.Integer
是两个不同的东西。 create
期望它的第一个和第三个参数与类型参数的类型相同。您将参数指定为 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)
我有 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);
}
即类型参数不匹配。
两者都是同一个 class 中的重载方法。 如何让 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: T, x: Int*)org.jaitools.numeric.Range[T] <and>
[T <: Number with Comparable[_]](x: T, x: Boolean, x: T, x: 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)
也许这也是
你的问题是 Int
和 java.lang.Integer
是两个不同的东西。 create
期望它的第一个和第三个参数与类型参数的类型相同。您将参数指定为 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)