4

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.

Johnneh
  • 247
  • 1
  • 10
  • 1
    Fun fact: When deleting `run(Function f)` the compiler complains `bad return type in lambda expression / void cannot be converted to String` – Socowi Jun 03 '18 at 21:05
  • [what research have you done](https://www.google.co.uk/search?ei=gFcUW7OmNabTgAaHsbnIAw&q=Consumer+and+Function+ambiguity+java&oq=Consumer+and+Function+ambiguity+java&gs_l=psy-ab.3...44323.45809.0.46047.9.9.0.0.0.0.110.728.7j1.8.0....0...1c.1.64.psy-ab..2.0.0....0.rn7w7_D_s5Q)? – Ousmane D. Jun 03 '18 at 21:06
  • 1
    Although it's not ideal, putting the body in braces fixes the issue: `run(x -> { System.out.println("test"); });` – Chris Smith Jun 03 '18 at 21:09
  • Another curiosity: `run(x -> new String("test"));` fails to compile as well because of ambiguity. – Johnneh Jun 03 '18 at 21:31
  • So the duplicates are a bug, thats marked as fixed for years now and a convoluted example with errors that got fixed and it works now! Well, I guess all is fine then. – Johnneh Jun 03 '18 at 21:35

0 Answers0