[英]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.