Ambiguous reference to overloaded definition

scala

This is an interesting problem. Details can be found in this post.

I try to call an overloaded method from java which works well in java but it reports such error in Scala. Scala cannot figure out the correct method if one method contains varargs as varargs can be 0 arg in Scala. See:

public class Util {
  public static String csv(Object s1) {
    return s1.toString();
  }

  public static String csv(Object s1, Object... strs) {
    if (strs.length == 0) {
      return s1.toString();
    } else {
      StringBuilder sb = new StringBuilder();
      sb.append(s1);
      for (Object s : strs) {
        sb.append(",");
        sb.append(s);
      }
      return sb.toString();
    }
  }

  public static void main(String[] args) {
    System.out.println(csv("a"));
    System.out.println(csv("a", "b", "c"));
  }
}

You cannot call Util.csv("hi") in Scala. As the two versions of csv method can both be applied to the single parameter. A way to fix it is to cal it by Util.csv(”hi”, Seq.empty :_*).

Also, there is a thing called auto-tupling. It’s an implicit conversion that can auto convert multiple args to Tuple if needed. Consider that there’s a method f(x: Any) which accepts a single parameter, but we call it by f(1, 2, 3). In order to make it work, Scala will auto convert the args to a Tuple (1, 2, 3), Tuple is compatible to Any, AnyRef, Object apparently.