The following class will not compile:
public class Thing {
public static <T> T foo(java.util.function.Supplier<T> supplier) {
return supplier.get();
}
public static <T> T bar(java.util.function.Function<Integer, T> function) {
return function.apply(42);
}
public static void main(String... args) {
System.out.println(foo(() -> "hello")); // 1
System.out.println(bar(any -> "hello")); // 2 !!!
System.out.println(bar((Integer any) -> "hello")); // 3
System.out.println(Thing.<String>bar(any -> "hello")); // 4
println(bar(any -> "hello")); // 5
}
private static void println(String string) {
System.out.println(string);
}
}
The issue is on line [2] in the main() method (all other lines are fine):
[ERROR] .../Thing.java:[13,19] reference to println is ambiguous
both method println(char[]) in java.io.PrintStream and method println(java.lang.String) in java.io.PrintStream match
[ERROR] .../Thing.java:[13,31] incompatible types: inference variable T has incompatible bounds
lower bounds: char[],java.lang.Object
lower bounds: java.lang.String
I don't understand why the compiler thinks there is an ambiguity on the return type of bar() (char[] or String) and can't decide which flavor of println() method should be used. On line [1], it can infer that the return type of foo() is String and on line [3], I don't understand how specifying the type of any (Integer) helps because it could not be anything else given the signature of the bar() method.