Why does the Scala compiler disallow overloaded methods with default arguments?
It would be very hard to get a readable and precise spec for the interactions of overloading resolution with default arguments. Of course, for many individual cases, like the one presented here, it's easy to say what should happen. But that is not enough. We'd need a spec that decides all possible corner cases. Overloading resolution is already very hard to specify. Adding default arguments in the mix would make it harder still. That's why we have opted to separate the two.
I can't answer your question, but here is a workaround:
implicit def left2Either[A,B](a:A):Either[A,B] = Left(a)
implicit def right2Either[A,B](b:B):Either[A,B] = Right(b)
def foo(a: Either[Int, String], b: Int = 42) = a match {
case Left(i) => i + b
case Right(s) => s + b
}
If you have two very long arg lists which differ in only one arg, it might be worth the trouble...
What worked for me is to redefine (Java-style) the overloading methods.
def foo(a: Int, b: Int) = a + b
def foo(a: Int, b: String) = a + b
def foo(a: Int) = a + "42"
def foo(a: String) = a + "42"
This ensures the compiler what resolution you want according to the present parameters.
I'd like to cite Lukas Rytz (from here):
The reason is that we wanted a deterministic naming-scheme for the generated methods which return default arguments. If you write
def f(a: Int = 1)
the compiler generates
def f$default$1 = 1
If you have two overloads with defaults on the same parameter position, we would need a different naming scheme. But we want to keep the generated byte-code stable over multiple compiler runs.
A solution for future Scala version could be to incorporate type names of the non-default arguments (those at the beginning of a method, which disambiguate overloaded versions) into the naming schema, e.g. in this case:
def foo(a: String)(b: Int = 42) = a + b
def foo(a: Int) (b: Int = 42) = a + b
it would be something like:
def foo$String$default$2 = 42
def foo$Int$default$2 = 42
Someone willing to write a SIP proposal?