Java 8 – ternary operator return function not compiled

Can anyone tell me why not compile?

public class TestClass {

    private boolean doThis = false;

    protected void fooThat() {}

    protected void fooThis() {}

    public void execute() {
        (doThis ? this::fooThis : this::fooThat).run();
    }
}

Solution

What do you want

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

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

I don't know who this is better than

if (doThis)
    fooThis();
else
    fooThat();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>