I've come across a weird problem where a method reference to Thread::sleep is ambiguous but a method with the same signature is not.
package test;
public class Test
{
public static void main(String[] args)
{
foo(Test::sleep, 1000L); //fine
foo((FooVoid<Long>)Thread::sleep, 1000L); //fine
foo(Thread::sleep, 1000L); //error
}
public static void sleep(long millis) throws InterruptedException
{
Thread.sleep(millis);
}
public static <P, R> void foo(Foo<P, R> function, P param) {}
public static <P> void foo(FooVoid<P> function, P param) {}
#FunctionalInterface
public interface Foo<P, R> {
R call(P param1) throws Exception;
}
#FunctionalInterface
public interface FooVoid<P> {
void call(P param1) throws Exception;
}
}
I get those 2 errors:
Error:(9, 17) java: reference to foo is ambiguous
both method <P,R>foo(test.Test.Foo<P,R>,P) in test.Test and method <P>foo(test.Test.FooVoid<P>,P) in test.Test match
Error:(9, 20) java: incompatible types: cannot infer type-variable(s) P,R
(argument mismatch; bad return type in method reference
void cannot be converted to R)
The only difference I see is that Thread::sleep is native. Does it change anything? I don't think the overload Thread::sleep(long, int) comes into play here. Why does it happen?
EDIT: Using javac version 1.8.0_111
You can recreate the problem in your own class by adding a method sleep with two arguments to class Test like below:
public static void sleep(long millis) {
}
public static void sleep(long millis, int nanos) {
}
So the problem is really caused by the fact that the method sleep is overloaded.
The JLS indicates that the initial method selection code only looks at the number of type arguments to the functional interface - only in the second phase does it look at the signature of the method inside the functional interface.
JLS 15.13:
It is not possible to specify a particular signature to be matched,
for example, Arrays::sort(int[]). Instead, the functional interface
provides argument types that are used as input to the overload
resolution algorithm (§15.12.2).
(the second-to-last paragraph of this section)
So in the case of Thread::sleep, void sleep(long) potentially matches functional interface FooVoid<P>, while overload void sleep(long, int) potentially matches functional interface Foo<P, R>. That's why you get the "reference to foo is ambiguous" error.
When it tries to go further and see how to match Foo<P, R> with functional method R call(P param1) to the method void sleep(long, int), it finds out that this is not actually possible, and you get another compile error:
test/Test.java:7: error: incompatible types: cannot infer type-variable(s) P,R
foo(Thread::sleep, 1000L); // error
^
(argument mismatch; bad return type in method reference
void cannot be converted to R)
The problem is that both, Thread.sleep and foo, are overloaded. So there is a circular dependency.
In order to find out which sleep method to use, we need to know the target type, i.e. which foo method to invoke
In order to find out which foo method to invoke, we need to know the functional signature of the argument, i.e. which sleep method we have selected
While it’s clear to a human reader that for this scenario only one of the 2×2 combinations is valid, the compiler must follow formal rules that work for arbitrary combinations, therefore, the language designers had to make a cut.
For the sake of usefulness of method references, there is a special treatment for unambiguous references, like your Test::sleep:
JLS §15.13.1
For some method reference expressions, there is only one possible compile-time declaration with only one possible invocation type (§15.12.2.6), regardless of the targeted function type. Such method reference expressions are said to be exact. A method reference expression that is not exact is said to be inexact.
Note that this distinction is similar to the distinction between implicitly typed lambda expressions (arg -> expression) and explicitly typed lambda expressions ((Type arg) -> expression).
When you look at JLS, §15.12.2.5., Choosing the Most Specific Method, you’ll see that the signature of a method reference is only used for exact method references, as when choosing the right foo, the decision for the right sleep method has not made yet.
If e is an exact method reference expression (§15.13.1), then i) for all i (1 ≤ i ≤ k), Ui is the same as Vi, and ii) one of the following is true:
R₂ is void.
R₁ <: R₂.
R₁ is a primitive type, R₂ is a reference type, and the compile-time declaration for the method reference has a return type which is a primitive type.
R₁ is a reference type, R₂ is a primitive type, and the compile-time declaration for the method reference has a return type which is a reference type.
The above rule has been stated in §15.12.2.5. for non-generic methods, redirecting to §18.5.4 for generic methods (which applies here as your foo methods are generic), containing exactly the same rule with a slightly different wording.
Since the method reference’s signature is not considered when choosing the most specific method, there is no most specific method and the invocation of foo is ambiguous. The second compiler error is the result of the strategy to continue processing the source code and potentially reporting more errors, instead of stopping the compilation right at the first error. One of the two invocations of foo caused an “incompatible types” error, if that invocation was happening, but actually that has been ruled out due to the “ambiguous invocation” error.
Personally I see this as some sort of recursion, somehow like this: we need to resolve the method in order to find the target type, but we need to know the target type in order to resolve the method. This has something to do with a special void compatibility rule, but I admit I do not entirely get it.
Things are even funner when you have something like this:
public static void cool(Predicate<String> predicate) {
}
public static void cool(Function<String, Integer> function) {
}
And try to call it via:
cool(i -> "Test"); // this will fail compilation
And btw if you make your lambda explicit, this will work:
foo((Long t) -> Thread.sleep(t), 1000L);
Related
Consider the following article from the JLS (§15.13.1)
A method reference expression ending with Identifier is exact if it satisfies all of the following:
If the method reference expression has the form ReferenceType ::[TypeArguments] Identifier, then ReferenceType does not denote a raw type.
The type to search has exactly one member method with the name Identifier that is accessible to the class or interface in which the method reference expression appears.
This method is not variable arity (§8.4.1).
If this method is generic (§8.4.4), then the method reference expression provides
TypeArguments.
Consider the following code snippet:
class Scratch {
public static void main(String[] args) {
Scratch.funct(new ImplementingClass()::<Functional1>hitIt);
}
public static void funct(Functional1 a){}
public static void funct(Functional2 a){}
}
interface Functional1 {<T> T hitIt();}
interface Functional2 {<T> T hitIt();}
class ImplementingClass{
public <T> T hitIt(){return null;}
}
Clearly - this satisfies all the conditions being mentioned for a method reference to be exact.
Not sure why still the method reference is in-exact in this particular case? Am I missing something here from the clause?
Solution :
Based on inputs from #Sweeper #DidierL and #Holger here what I summarized:
Both the functional interfaces have the functionType <T> () -> T
the method reference …::<Functional1>hitIt substitutes T with Functional1, so the resulting functional signature is () -> Functional1 which does not match <T> () -> T.
First a warning: IANAJL (IANAL for Java 😉)
As far as I can tell, this should compile if you make the two interface methods non-generic, but it doesn’t. Let’s simplify the code as much as we can to reproduce the problem:
class Scratch {
public static void main(String[] args) {
Scratch.funct(ImplementingClass::<Void>hitIt);
}
public static void funct(Functional1 a){}
public static void funct(Functional2 a){}
}
interface Functional1 {Integer hitIt();}
interface Functional2 {String hitIt();}
class ImplementingClass{
public static <T> Integer hitIt(){return null;}
}
The simplifications:
the two interfaces now have non-generic methods
ImplementingClass.hitIt() is now static and has a concrete return type (non-generic)
Now let’s analyze the call to check if it should compile. I put links to the Java 8 specs but they are very similar in 17.
15.12.2.1. Identify Potentially Applicable Methods
A member method is potentially applicable to a method invocation if and only if all of the following are true:
[…]
If the member is a fixed arity method with arity n, the arity of the method invocation is equal to n, and for all i (1 ≤ i ≤ n), the i'th argument of the method invocation is potentially compatible, as defined below, with the type of the i'th parameter of the method.
[…]
An expression is potentially compatible with a target type according to the following rules:
[…]
A method reference expression (§15.13) is potentially compatible with a functional interface type if, where the type's function type arity is n, there exists at least one potentially applicable method for the method reference expression with arity n (§15.13.1), and one of the following is true:
The method reference expression has the form ReferenceType :: [TypeArguments] Identifier and at least one potentially applicable method is i) static and supports arity n, or ii) not static and supports arity n-1.
The method reference expression has some other form and at least one potentially applicable method is not static.
(this last bullet applies for the case of the question where the method reference uses a constructor invocation expression, i.e. a Primary)
At this point, we only check for the arity of the method reference, so both funct() methods are potentially applicable.
15.12.2.2. Phase 1: Identify Matching Arity Methods Applicable by Strict Invocation
An argument expression is considered pertinent to applicability for a potentially applicable method m unless it has one of the following forms:
[…]
An inexact method reference expression (§15.13.1).
[…]
This is the only bullet point in this list that could potentially match, however, as pointed in the question we have an exact method reference expression here. Note that if you remove the <Void>, this makes it an inexact method reference, and both methods should be applicable as per the next section:
Let m be a potentially applicable method (§15.12.2.1) with arity n and formal parameter types F1 ... Fn, and let e1, ..., en be the actual argument expressions of the method invocation. Then:
[…]
If m is not a generic method, then m is applicable by strict invocation if, for 1 ≤ i ≤ n, either ei is compatible in a strict invocation context with Fi or ei is not pertinent to applicability.
However only the first funct() method declaration should be applicable by strict invocation. Strict invocation contexts are defined here, but basically they check if the type of the expression matches the type of the argument. Here the type of our argument, the method reference, is defined by section 15.13.2. Type of a Method Reference whose relevant part is:
A method reference expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of […] T.
[…]
A method reference expression is congruent with a function type if both of the following are true:
The function type identifies a single compile-time declaration corresponding to the reference.
One of the following is true:
The result of the function type is void.
The result of the function type is R, and the result of applying capture conversion (§5.1.10) to the return type of the invocation type (§15.12.2.6) of the chosen compile-time declaration is R' (where R is the target type that may be used to infer R'), and neither R nor R' is void, and R' is compatible with R in an assignment context.
Here R would be Integer for Functional1 and String for Functional2, while R' is Integer in both cases (since there is no capture conversion needed for ImplementingClass.hitIt()), so clearly the method reference is not congruent with Functional2 and by extension not compatible.
funct(Functional2) should thus not be considered for applicability by strict invocation, and since only funct(Functional1) remains it should be selected.
It should be noted that Javac must select both methods in Phase 1, because only one phase can apply, and Phase 2 only uses loose context instead of strict, which just allows boxing operations, and Phase 3 then includes varargs, which is not applicable either.
Except if we consider that Javac somehow considers the method reference as congruent with Functional2, the only reason I see for selecting both methods is if it considered the method reference as not pertinent for applicability as specified above, which I can only explain if the compiler considers it as an inexact method reference.
15.12.2.5. Choosing the Most Specific Method
This is where the compilation fails. We should note that there is nothing here that would make the compiler select one method over the other. The applicable rule is:
m2 is not generic, and m1 and m2 are applicable by strict or loose invocation, and where m1 has formal parameter types S1, ..., Sn and m2 has formal parameter types T1, ..., Tn, the type Si is more specific than Ti for argument ei for all i (1 ≤ i ≤ n, n = k).
[…]
A type S is more specific than a type T for any expression if S <: T (§4.10).
This appears to work properly: change Functional2 to extend Functional1 and it will compile.
A functional interface type S is more specific than a functional interface type T for an expression e if T is not a subtype of S and one of the following is true (where U1 ... Uk and R1 are the parameter types and return type of the function type of the capture of S, and V1 ... Vk and R2 are the parameter types and return type of the function type of T):
If e is an explicitly typed lambda expression […]
If e is an exact method reference expression (§15.13.1), then i) for all i (1 ≤ i ≤ k), Ui is the same as Vi, and ii) one of the following is true:
R2 is void.
R1 <: R2.
[…]
This does not allow to disambiguate it either. However, changing Functional2.hitIt() to return Number should make Functional1 more specific since Integer <: Number.
This still fails, which seems to confirm that the compiler does not consider it as an exact method reference.
Note that removing the <T> in ImplementingClass.hitIt() allows it to compile, independently of the return type of Functional2.hitIt(). Fun fact: you can leave the <Void> at the call site, the compiler ignores it.
Even stranger: if you leave the <T> and add more type arguments than required at the call site, the compiler still complains about the ambiguous call and not about the number of type arguments (until you remove the ambiguity). Not that this should make the method reference inexact, based on the above definition, but I would think it should be checked first.
Conclusion
Since the Eclipse compiler accepts it, I would tend to consider this as a Javac bug, but note that the Eclipse compiler is sometimes more lenient than Javac with respect to the specs, and some similar bugs have been reported and closed (JDK-8057895, JDK-8170842, …).
I am using a lambda to implement a functional interface in the Java program below. When the lambda is passed as an argument to a generic method, the compiler flags an "incompatible types" error because it infers that the lambda implements the Func<Shape> interface, which has the compiler interpreting the lambda parameter ("thing") as being of type Shape when the lambda attempts to pass it to a method (testRound) that requires an argument of type Round. That error makes sense to me.
But the equivalent method reference does not provoke an error message. I had been under the misconception that a lambda and a method reference that could replace that lambda were interchangeable. Here, that's not so.
public class Main
{
public static void main(String... args)
{
methodB(thing -> Main.testRound(thing)); // incompatible types
methodB(Main::testRound); // no problem here
}
static <T extends Shape> void methodB(Func<T> function)
{
}
static boolean testRound(Round thing)
{
return true;
}
}
interface Func<T>
{
boolean test(T ob);
}
class Shape
{
}
class Round extends Shape
{
}
Why does the method reference succeed when the lambda fails?
UPDATE
Vince Emigh found the answer, which I've marked as accepted, below. While it's not part of my question, here are four ways to work around the fact that the lambda is only inferred as being of type Func<Shape> if one were really stuck on using lambdas:
// Use a type witness.
Main.<Round>methodB(thing -> testRound(thing));
// Make the lambda's argument type explicit.
methodB((Round thing) -> testRound(thing));
// Cast the argument.
methodB(thing -> testRound((Round)thing));
// Store the lambda reference in a Func<Round> variable.
Func<Round> lambda = thing -> testRound(thing);
methodB(lambda);
I don't see any reason to prefer one of these over the method reference, unless one feels that lambdas are a little less dense (and, maybe, a little more readable). But, they're there if you want them.
From JLS §15.13.2:
Unlike a lambda expression, a method reference can be congruent with a generic function type (that is, a function type that has type parameters). This is because the lambda expression would need to be able to declare type parameters, and no syntax supports this; while for a method reference, no such declaration is necessary.
The lambda expression raises an error since there is no type argument specified. This causes T to be compiled as Shape (as mentioned in your post), since there's nothing to help infer the argument's type.
As for method references, since the type can be inferred from the method's parameters, no explicit type argument is needed, as mentioned in the JLS statement above.
Consider the following program:
public class GenericTypeInference {
public static void main(String[] args) {
print(new SillyGenericWrapper().get());
}
private static void print(Object object) {
System.out.println("Object");
}
private static void print(String string) {
System.out.println("String");
}
public static class SillyGenericWrapper {
public <T> T get() {
return null;
}
}
}
It prints "String" under Java 8 and "Object" under Java 7.
I would have expected this to be an ambiguity in Java 8, because both overloaded methods match. Why does the compiler pick print(String) after JEP 101?
Justified or not, this breaks backward compatibility and the change cannot be detected at compile time. The code just sneakily behaves differently after upgrading to Java 8.
NOTE: The SillyGenericWrapper is named "silly" for a reason. I'm trying to understand why the compiler behaves the way it does, don't tell me that the silly wrapper is a bad design in the first place.
UPDATE: I've also tried to compile and run the example under Java 8 but using a Java 7 language level. The behavior was consistent with Java 7. That was expected, but I still felt the need to verify.
The rules of type inference have received a significant overhaul in Java 8; most notably target type inference has been much improved. So, whereas before Java 8 the method argument site did not receive any inference, defaulting to Object, in Java 8 the most specific applicable type is inferred, in this case String. The JLS for Java 8 introduced a new chapter Chapter 18. Type Inference that's missing in JLS for Java 7.
Earlier versions of JDK 1.8 (up until 1.8.0_25) had a bug related to overloaded methods resolution when the compiler successfully compiled code which according to JLS should have produced ambiguity error Why is this method overloading ambiguous? As Marco13 points out in the comments
This part of the JLS is probably the most complicated one
which explains the bugs in earlier versions of JDK 1.8 and also the compatibility issue that you see.
As shown in the example from the Java Tutoral (Type Inference)
Consider the following method:
void processStringList(List<String> stringList) {
// process stringList
}
Suppose you want to invoke the method processStringList with an empty list. In Java SE 7, the following statement does not compile:
processStringList(Collections.emptyList());
The Java SE 7 compiler generates an error message similar to the following:
List<Object> cannot be converted to List<String>
The compiler requires a value for the type argument T so it starts with the value Object. Consequently, the invocation of Collections.emptyList returns a value of type List, which is incompatible with the method processStringList. Thus, in Java SE 7, you must specify the value of the value of the type argument as follows:
processStringList(Collections.<String>emptyList());
This is no longer necessary in Java SE 8. The notion of what is a target type has been expanded to include method arguments, such as the argument to the method processStringList. In this case, processStringList requires an argument of type List
Collections.emptyList() is a generic method similar to the get() method from the question. In Java 7 the print(String string) method is not even applicable to the method invocation thus it doesn't take part in the overload resolution process. Whereas in Java 8 both methods are applicable.
This incompatibility is worth mentioning in the Compatibility Guide for JDK 8.
You can check out my answer for a similar question related to overloaded methods resolution Method overload ambiguity with Java 8 ternary conditional and unboxed primitives
According to JLS 15.12.2.5 Choosing the Most Specific Method:
If more than one member method is both accessible and applicable to a
method invocation, it is necessary to choose one to provide the
descriptor for the run-time method dispatch. The Java programming
language uses the rule that the most specific method is chosen.
Then:
One applicable method m1 is more specific than another applicable
method m2, for an invocation with argument expressions e1, ..., ek, if
any of the following are true:
m2 is generic, and m1 is inferred to be more specific than m2 for
argument expressions e1, ..., ek by §18.5.4.
m2 is not generic, and m1 and m2 are applicable by strict or loose
invocation, and where m1 has formal parameter types S1, ..., Sn and m2
has formal parameter types T1, ..., Tn, the type Si is more specific
than Ti for argument ei for all i (1 ≤ i ≤ n, n = k).
m2 is not generic, and m1 and m2 are applicable by variable arity
invocation, and where the first k variable arity parameter types of m1
are S1, ..., Sk and the first k variable arity parameter types of m2
are T1, ..., Tk, the type Si is more specific than Ti for argument ei
for all i (1 ≤ i ≤ k). Additionally, if m2 has k+1 parameters, then
the k+1'th variable arity parameter type of m1 is a subtype of the
k+1'th variable arity parameter type of m2.
The above conditions are the only circumstances under which one method may be more specific than another.
A type S is more specific than a type T for any expression if S <: T (§4.10).
The second of three options matches our case. Since String is a subtype of Object (String <: Object) it is more specific. Thus the method itself is more specific. Following the JLS this method is also strictly more specific and most specific and is chosen by the compiler.
In java7, expressions are interpreted from bottom up (with very few exceptions); the meaning of a sub-expression is kind of "context free". For a method invocation, the types of the arguments are resolved fist; the compiler then uses that information to resolve the meaning of the invocation, for example, to pick a winner among applicable overloaded methods.
In java8, that philosophy does not work anymore, because we expect to use implicit lambda (like x->foo(x)) everywhere; the lambda parameter types are not specified and must be inferred from context. That means, for method invocations, sometimes the method parameter types decide the argument types.
Obviously there's a dilemma if the method is overloaded. Therefore in some cases, it's necessary to resolve method overloading first to pick one winner, before compiling the arguments.
That is a major shift; and some old code like yours will fall victim to incompatibility.
A workaround is to provide a "target typing" to the argument with "casting context"
print( (Object)new SillyGenericWrapper().get() );
or like #Holger's suggestion, provide type parameter <Object>get() to avoid inference all together.
Java method overloading is extremely complicated; the benefit of the complexity is dubious. Remember, overloading is never a necessity - if they are different methods, you can give them different names.
First of all it has nothing to do with overriding , but it has to deal with overloading.
Jls,. Section 15 provides lot of information on how exactly compiler selects the overloaded method
The most specific method is chosen at compile time; its descriptor
determines what method is actually executed at run time.
So when invoking
print(new SillyGenericWrapper().get());
The compiler choose String version over Object because print method that takes String is more specific then the one that takes Object. If there was Integer instead of String then it will get selected.
Moreover if you want to invoke method that takes Object as a parameter then you can assign the return value to the parameter of type object E.g.
public class GenericTypeInference {
public static void main(String[] args) {
final SillyGenericWrapper sillyGenericWrapper = new SillyGenericWrapper();
final Object o = sillyGenericWrapper.get();
print(o);
print(sillyGenericWrapper.get());
}
private static void print(Object object) {
System.out.println("Object");
}
private static void print(Integer integer) {
System.out.println("Integer");
}
public static class SillyGenericWrapper {
public <T> T get() {
return null;
}
}
}
It outputs
Object
Integer
The situation starts to become interesting when let say you have 2 valid method definations that are eligible for overloading. E.g.
private static void print(Integer integer) {
System.out.println("Integer");
}
private static void print(String integer) {
System.out.println("String");
}
and now if you invoke
print(sillyGenericWrapper.get());
The compiler will have 2 valid method definition to choose from , Hence you will get compilation error because it cannot give preference to one method over the other.
I ran it using Java 1.8.0_40 and got "Object".
If you'll run the following code:
public class GenericTypeInference {
private static final String fmt = "%24s: %s%n";
public static void main(String[] args) {
print(new SillyGenericWrapper().get());
Method[] allMethods = SillyGenericWrapper.class.getDeclaredMethods();
for (Method m : allMethods) {
System.out.format("%s%n", m.toGenericString());
System.out.format(fmt, "ReturnType", m.getReturnType());
System.out.format(fmt, "GenericReturnType", m.getGenericReturnType());
}
private static void print(Object object) {
System.out.println("Object");
}
private static void print(String string) {
System.out.println("String");
}
public static class SillyGenericWrapper {
public <T> T get() {
return null;
}
}
}
You will see that you get:
Object public T
com.xxx.GenericTypeInference$SillyGenericWrapper.get()
ReturnType: class java.lang.Object
GenericReturnType: T
Which explains why the method overloaded with Object is used and not the String one.
OK, so method overloading is-a-bad-thing™. Now that this has been settled, let's assume I actually want to overload a method like this:
static void run(Consumer<Integer> consumer) {
System.out.println("consumer");
}
static void run(Function<Integer, Integer> function) {
System.out.println("function");
}
In Java 7, I could call them easily with non-ambiguous anonymous classes as arguments:
run(new Consumer<Integer>() {
public void accept(Integer integer) {}
});
run(new Function<Integer, Integer>() {
public Integer apply(Integer o) { return 1; }
});
Now in Java 8, I'd like to call those methods with lambda expressions of course, and I can!
// Consumer
run((Integer i) -> {});
// Function
run((Integer i) -> 1);
Since the compiler should be able to infer Integer, why don't I leave Integer away, then?
// Consumer
run(i -> {});
// Function
run(i -> 1);
But this doesn't compile. The compiler (javac, jdk1.8.0_05) doesn't like that:
Test.java:63: error: reference to run is ambiguous
run(i -> {});
^
both method run(Consumer<Integer>) in Test and
method run(Function<Integer,Integer>) in Test match
To me, intuitively, this doesn't make sense. There is absolutely no ambiguity between a lambda expression that yields a return value ("value-compatible") and a lambda expression that yields void ("void-compatible"), as set out in the JLS §15.27.
But of course, the JLS is deep and complex and we inherit 20 years of backwards compatibility history, and there are new things like:
Certain argument expressions that contain implicitly typed lambda expressions (§15.27.1) or inexact method references (§15.13.1) are ignored by the applicability tests, because their meaning cannot be determined until a target type is selected.
from JLS §15.12.2
The above limitation is probably related to the fact that JEP 101 wasn't implemented all the way, as can be seen here and here.
Question:
Who can tell me exactly what parts of the JLS specifies this compile-time ambiguity (or is it a compiler bug)?
Bonus: Why were things decided this way?
Update:
With jdk1.8.0_40, the above compiles and works fine
I think you found this bug in the compiler: JDK-8029718 (or this similar one in Eclipse: 434642).
Compare to JLS §15.12.2.1. Identify Potentially Applicable Methods:
…
A lambda expression (§15.27) is potentially compatible with a functional interface type (§9.8) if all of the following are true:
The arity of the target type's function type is the same as the arity of the lambda expression.
If the target type's function type has a void return, then the lambda body is either a statement expression (§14.8) or a void-compatible block (§15.27.2).
If the target type's function type has a (non-void) return type, then the lambda body is either an expression or a value-compatible block (§15.27.2).
Note the clear distinction between “void compatible blocks” and “value-compatible blocks”. While a block might be both in certain cases, the section §15.27.2. Lambda Body clearly states that an expression like () -> {} is a “void compatible block”, as it completes normally without returning a value. And it should be obvious that i -> {} is a “void compatible block” too.
And according to the section cited above, the combination of a lambda with a block that is not value-compatible and target type with a (non-void) return type is not a potential candidate for the method overload resolution. So your intuition is right, there should be no ambiguity here.
Examples for ambiguous blocks are
() -> { throw new RuntimeException(); }
() -> { while (true); }
as they don’t complete normally, but this is not the case in your question.
This bug has already been reported in the JDK Bug System: https://bugs.openjdk.java.net/browse/JDK-8029718. As you can check the bug has been fixed. This fix syncs javac with the spec in this aspect. Right now javac is correctly accepting the version with implicit lambdas. To get this update, you need to clone javac 8 repo.
What the fix does is to analyze the lambda body and determine if it's void or value compatible. To determine this you need to analyze all return statements. Let's remember that from the spec (15.27.2), already referenced above:
A block lambda body is void-compatible if every return statement in
the block has the form return.
A block lambda body is value-compatible if it cannot complete
normally (14.21) and every return statement in the block has the
form return Expression.
This means that by analyzing the returns in the lambda body you can know if the lambda body is void compatible but to determine if it's value compatible you also need to do a flow analysis on it to determine that it can complete normally (14.21).
This fix also introduces a new compiler error for cases when the body is neither void nor value compatible, for example if we compile this code:
class Test {
interface I {
String f(String x);
}
static void foo(I i) {}
void m() {
foo((x) -> {
if (x == null) {
return;
} else {
return x;
}
});
}
}
the compiler will give this output:
Test.java:9: error: lambda body is neither value nor void compatible
foo((x) -> {
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
I hope this helps.
Lets assume we have method and method call
void run(Function<Integer, Integer> f)
run(i->i)
What methods can we legally add?
void run(BiFunction<Integer, Integer, Integer> f)
void run(Supplier<Integer> f)
Here the parameter arity is different, specifically the i-> part of i->i does not fit the parameters of apply(T,U) in BiFunction, or get() in Supplier. So here any possible ambiguities are defined by parameter arity, not types, and not the return.
What methods can't we add?
void run(Function<Integer, String> f)
This gives a compiler error as run(..) and run(..) have the same erasure. So as the JVM can't support two functions with the same name and argument types, this can't be compiled. So the compiler never has to resolve ambiguities in this type of scenario as they are explicitly disallowed due the rules preexisting in the Java type system.
So that leaves us with other functional types with a parameter arity of 1.
void run(IntUnaryOperator f)
Here run(i->i) is valid for both Function and IntUnaryOperator, but this will refuse to compile due to reference to run is ambiguous as both functions match this lambda. Indeed they do, and an error here is to be expected.
interface X { void thing();}
interface Y { String thing();}
void run(Function<Y,String> f)
void run(Consumer<X> f)
run(i->i.thing())
Here this fails to compile, again due to ambiguities. Without knowing the type of i in this lambda it is impossible to know the type of i.thing(). We therefore accept that this is ambiguous and rightly fails to compile.
In your example:
void run(Consumer<Integer> f)
void run(Function<Integer,Integer> f)
run(i->i)
Here we know that both of functional types have a single Integer parameter, so we know that the i in i-> must be an Integer. So we know that it must be run(Function) that is called. But the compiler doesn't try to do this. This is the first time that the compiler does something that we don't expect.
Why does it not do this? I'd say because it is a very specific case, and inferring the type here requires mechanisms that we have not seen for any of the other above cases, because in the general case they are unable to correctly infer the type and choose the correct method.
public void add(long... x){}
public void add(Integer... x){}
add(2);
this produces error...why overlaoding is not performed with both widening and boxing?
but overloading without vararg works fine
public void add(long x){}
public void add(Integer x){}
add(2);
here add(long x) will be executed that is widening beats boxing...why not same concept with
var arguments
Java compiler performs three attempts to choose an appropriate method overload (JLS §15.12.2.1):
Phase 1: Identify Matching Arity Methods Applicable by Subtyping
(possible boxing conversions and methods with varargs are ignored)
Phase 2: Identify Matching Arity Methods Applicable by Method
Invocation Conversion
(takes boxing conversion in account, but ignores methods with varargs)
Phase 3: Identify Applicable Variable Arity Methods
(examines all possibilities)
So, with your examples it works as follows:
Without varargs: add(long x) is identified as the only applicable method on the 1st phase (this method is applicable by subtyping since int is a subtype of long, §JLS 4.10.1), so that following phases are not executed.
With varargs: overload resoltion algorithm goes to phase 3, where both methods are identified as applicable, and compiler can't choose the most specific method of them (choosing the most specific method is yet another complex algorithm), therefore it reports ambiguity.
See also:
The Java Language Specification, Seventh Edition
because it is ambiguous.
2 can be Integer as well as long and it can be resolve to both. you made compiler confused whom to invoke :)
5.12.2.2 Choose the Most Specific Method
If more than one method declaration is
both accessible and applicable to a
method invocation, it is necessary to
choose one to provide the descriptor
for the run-time method dispatch. The
Java programming language uses the
rule that the most specific method is
chosen. The informal intuition is that
one method declaration is more
specific than another if any
invocation handled by the first method
could be passed on to the other one
without a compile-time type error.
The precise definition is as follows.
Let m be a name and suppose that there
are two declarations of methods named
m, each having n parameters. Suppose
that one declaration appears within a
class or interface T and that the
types of the parameters are T1, . . .
, Tn; suppose moreover that the other
declaration appears within a class or
interface U and that the types of the
parameters are U1, . . . , Un. Then
the method m declared in T is more
specific than the method m declared in
U if and only if both of the following
are true:
T can be converted to U by method
invocation conversion. Tj can be
converted to Uj by method invocation
conversion, for all j from 1 to n. A
method is said to be maximally
specific for a method invocation if it
is applicable and accessible and there
is no other applicable and accessible
method that is more specific. If there
is exactly one maximally specific
method, then it is in fact the most
specific method; it is necessarily
more specific than any other method
that is applicable and accessible. It
is then subjected to some further
compile-time checks as described in
§15.12.3.
It is possible that no method is the
most specific, because there are two
or more maximally specific methods. In
this case:
If all the maximally specific methods
have the same signature, then: If one
of the maximally specific methods is
not declared abstract, it is the most
specific method. Otherwise, all the
maximally specific methods are
necessarily declared abstract. The
most specific method is chosen
arbitrarily among the maximally
specific methods. However, the most
specific method is considered to throw
a checked exception if and only if
that exception is declared in the
throws clauses of each of the
maximally specific methods. Otherwise,
we say that the method invocation is
ambiguous, and a compile-time error
occurs.
15.12.2.3 Example: Overloading Ambiguity
Consider the example:
class Point { int x, y; }
class ColoredPoint extends Point { int color; }
class Test {
static void test(ColoredPoint p, Point q) {
System.out.println("(ColoredPoint, Point)");
}
static void test(Point p, ColoredPoint q) {
System.out.println("(Point, ColoredPoint)");
}
public static void main(String[] args) {
ColoredPoint cp = new ColoredPoint();
test(cp, cp); // compile-time error
}
}
This example produces an error at compile time. The problem is that there are two declarations of test that are applicable and accessible, and neither is more specific than the other. Therefore, the method invocation is ambiguous.
If a third definition of test were added:
static void test(ColoredPoint p, ColoredPoint q) {
System.out.println("(ColoredPoint, ColoredPoint)");
}
then it would be more specific than the other two, and the method invocation would no longer be ambiguous.
Read More