redspider redspider - 7 months ago 20
Java Question

Java 8 - Ternary operator returning function doesn't compile

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();
}
}

Answer

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();