以下类将不会编译:
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);
}
}
该问题位于main()
方法的第[2]行(所有其他行都可以):
[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
我不理解为什么编译器认为返回类型bar()
(char[]
或String
)有歧义,并且不能决定应该使用println()
方法的哪种风格.在第[1]行,可以推断foo()
的返回类型是String
,在第[3]行,我不理解指定any
(Integer
)的类型有什么帮助,因为它不能是任何其他给定bar()
方法签名的方法.