Dollyg :
I have a Scala class which has two overloaded set
methods, one with an Array
param and the other with varargs
. I want to call these methods from Java side, I am facing some issues due to overloading and/or boxing/unboxing. It would be helpful if someone can explain the reason behind the issue I'm facing and/or suggest workarounds.
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")
}
}
Call from Java
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
}
som-snytt :
I guess it's because Scala results in
public <S extends java.lang.Object> void set(java.lang.Object);
instead of
<S extends java.lang.Object> void set(S[]);
I have no idea if that has to do with covariance of Arrays or what. (Edit: why generic array is erased to Object: Scala: arrays and type erasure)
Edit: Scala 3 output doesn't compile under Java at this time, probably because it hasn't forward-ported Scala 2 improvements.