I have Oracle-Java version 1.8.0_171
My Code:
public void test() {
run(x -> "1"); // calls run(Function)
run(x -> System.out.println("test")); // fails to compile
run(() -> System.out.println("test")); // calls run(Runnable)
run(() -> "1"); // calls run(Supplier)
}
void run(Consumer<Integer> c) {
System.out.println("Consumer");
}
void run(Function<Integer, String> f) {
System.out.println("Function");
}
void run(Supplier<String> s) {
System.out.println("Supplier");
}
void run(Runnable r) {
System.out.println("Runnable");
}
The compiler should be able to recognize, that void does not conform to String.
However it fails to compile the second line of test()
even with javac and I get:
both method run(Consumer<Integer>) in Test and method
run(Function<Integer,String>) in Test match
The first and last two lines of test()
compile fine, even though it should be the same problem.
What is the problem here? I want my library users to be able to pass any lambda (Function, Consumer, Supplier, Runnable) to the run method without having to use "the ugly" syntax.