3

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


    }
2
  • Thanks, I forgot to add that in sample, will correct that. But the problem remains, varargs overload doesn't get called when method is called with single element. Commented Feb 12, 2020 at 18:26
  • 1
    Java and Scala overload resolution works differently. There are tickets where this stumps everyone. Commented Feb 12, 2020 at 18:45

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.