这与方法引用调用有关,在lambda中,我们能够对具有不同返回类型的方法进行方法引用。参见下面的代码-

interface Sayable {
    void say();
}

class SayableImpl implements Sayable {

    @Override
    public boolean say() {
        // error wrong return type
    }
}

public class MethodReference {
    public static boolean saySomething() {
        System.out.println("Hello, this is static method.");
        return true;
    }

    public static void main(String[] args) {
        MethodReference methodReference = new MethodReference();
        Sayable sayable = () -> methodReference.saySomething();
        sayable.say();

        // Referring static method
        Sayable sayable2 = MethodReference::saySomething;
        sayable2.say();
    }
}


在这里,我们用say()实现void MethodReference::saySomething()方法,其返回类型为boolean

我们如何证明它合理?我想念什么吗?

最佳答案

因为你也可以写

class SayableImpl implements Sayable {
    @Override
    public void say() {
        new MethodReference().saySomething();
    }
}


这是您最终在使用lambda表示它时所要做的

Sayable sayable = () -> methodReference.saySomething()

关于java - java 8方法引用,允许不兼容的返回类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58528902/

10-10 17:32