Scala-Java interop, method overloading problems (arrays and variadic parameters)… here is a solution to the problem.
Scala-Java interop, method overloading problems (arrays and variadic parameters)
I have a Scala class that has two overloaded set
methods,
One with the Array
parameter and the other with varargs
.
I want to call these methods from the Java side, I’m facing some issues due to overloading and/or boxing/unboxing. It would be helpful if someone could explain the reason behind the problem I’m facing and/or suggest a workaround.
Scala class
class Sample {
def set[S](values: Array[S]): Unit = {
println("Array overload")
}
@varargs
def set[S](value: S, values: S*): Unit = {
println("Varargs overload")
}
}
Java calls
public static void main(String[] args) {
Sample sample = new Sample();
Boolean[] array = {true, false};
Boolean boxed = true;
boolean primitive = true;
works for array
sample.set(array); should call Array-overload, calls Array-overload
doesn't work for single element varargs
sample.set(boxed); should call varargs-overload, calls Array-overload instead
sample.set(primitive); should call varargs-overload, calls Array-overload instead
works for multiple varargs
sample.set(boxed, boxed); should call varargs-overload, varargs-overload is called
sample.set(primitive, primitive); should call varargs-overload, varargs-overload is called
}
Solution
I guess it’s because of Scala results
public <S extends java.lang.Object> void set(java.lang.Object);
Replace
<S extends java.lang.Object> void set(S[]);
I don’t know if this is related to the covariance of the array. (Edit: Why generic arrays are removed as objects: Scala: arrays and type erasure.) )
EDIT: Scala 3 output does not compile under Java at this time, probably because it does not have the improvements of forwardporting Scala 2.