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();
}
}
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();
The way to do it is as follows:
Runnable r = (doThis ? this::fooThis : this::fooThat);
r.run();
Your code does not compile because:
run()
later.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With