Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 - Ternary operator returning function doesn't compile

Tags:

java

java-8

Can anyone tell me why this does not compile?

public class TestClass {

    private boolean doThis = false;

    protected void fooThat() {}

    protected void fooThis() {}

    public void execute() {
        (doThis ? this::fooThis : this::fooThat).run();
    }
}
like image 881
redspider Avatar asked Apr 21 '16 12:04

redspider


2 Answers

What you intended is likely to be

(doThis ? this::fooThis : (Runnable) (this::fooThat)).run();

Java cannot infer from the method name alone what type you expect the ?: to return.

I am not sure this is better than

if (doThis)
    fooThis();
else
    fooThat();
like image 121
Peter Lawrey Avatar answered Oct 06 '22 01:10

Peter Lawrey


The way to do it is as follows:

Runnable r = (doThis ? this::fooThis : this::fooThat);
r.run();

Your code does not compile because:

  1. The ternary operator must be used when assigning a value. This is not the case in your code.
  2. Method references and lambda expressions must be matched to a functional interface in order to call its single abstract method later. In your code, you are not specifying any functional interface for your method references, so there is no type where to invoke the method run() later.
like image 45
fps Avatar answered Oct 06 '22 01:10

fps