Why is this Java method call considered ambiguous?
Your question is very similar to this one.
The short answer is:
Overloaded::genuinelyAmbiguous;
Overloaded::notAmbiguous;
Overloaded::strangelyAmbiguous;
all these method references are inexact (they have multiple overloads). Consequently, according to the JLS §15.12.2.2., they are skipped from the applicability check during overload resolution, which results in ambiguity.
In this case, you need to specify the type explicitly, for example:
load((Processor) Overloaded::genuinelyAmbiguous);
load(( Supplier) Overloaded::strangelyAmbiguous);
Method references and overloading, just... don't. Theoretically, you are more than correct - this should be fairly easy for a compiler to deduce, but let's not confuse humans and compilers.
The compiler sees a call to load
and says : "hey, I need to call that method. Cool, can I? Well there are 2 of them. Sure, let's match the argument". Well the argument is a method reference to an overloaded method. So the compiler is getting really confused here, it basically says that : "if I could tell which method reference you are pointing to, I could call load
, but, if I could tell which load
method you want to call, I could infer the correct strangelyAmbiguous
", thus it just goes in circles, chasing it's tale. This made up decision in a compilers "mind" is the simplest way I could think to explain it. This brings a golden bad practice - method overloading and method references are a bad idea.
But, you might say - ARITY! The number of arguments is the very first thing a compiler does (probably) when deciding if this is an overload or not, exactly your point about:
Processor p = Overloaded::strangelyAmbiguous;
And for this simple case, the compiler could indeed infer the correct methods, I mean we, humans can, should be a no brainer for a compiler. The problem here is that this is a simple case with just 2 methods, what about 100*100 choices? The designers had to either allow something (let' say up to 5*5 and allow resolution like this) or ban that entirely - I guess you know the path they took. It should be obvious why this would work if you would have used a lambda - arity is right there, explicit.
About the error message, this would not be anything new, if you play enough with lambdas and method references, you will start to hate the error message : "a non static method cannot be referenced from a static context", when there is literally nothing to do with that. IIRC these error messages have improved from java-8 and up, you never know if this error message would improve also in java-15, let's say.