简体   繁体   中英

Convert java to scala - overloaded static methods

I have java code like compiles fine.

import org.jaitools.numeric.Range;
Range<Integer> r1 = Range.create(1, true, 4, true);

Converted to Scala like

val r1: org.jaitools.numeric.Range[Integer] = org.jaitools.numeric.Range.create(1, true, 4, true)

compilation fails as java seems to go for this method:

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);
    }

whereas the Scala compiler will choose to use

public static <T extends Number & Comparable> Range<T> create(T value, int... inf) {
        return new Range<T>(value, inf);
}

ie the type arguments do not match.

Both are overloaded methods in the same class. How can I get the Scala compiler to choose the right method?

edit

val r1: org.jaitools.numeric.Range[Integer] = org.jaitools.numeric.Range.create(1, true, 4, true)

results in

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)

Maybe this is also a case of convert java to scala code - change of method signatures where the type system of java and Scala do not work well together?

Your problem is that Int and java.lang.Integer are two different things. create expects its first and third parameters to be of the same type as the type parameter. You are specifying the param as Integer but arguments you are passing in - 1 and 4 - are of type Int .

You cannot create Range[Int] , because the type parameter is required to extend Number and Comparable , which Int does not. So, you have to wrap your Int s into Integer explicitly

val r1 = org.jaitools.numeric.Range.create(Integer.valueOf(1), true, Integer.valueOf(4), true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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