【问题标题】:java8 method reference , allowing incompatiable return typejava 8 方法引用,允许不兼容的返回类型
【发布时间】:2019-10-23 18:21:53
【问题描述】:

这是关于方法引用调用,在 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();
    }
}

这里我们用MethodReference::saySomething()实现void say()方法,它的返回类型是boolean

我们如何证明它的合理性?我错过了什么吗?

【问题讨论】:

  • 但是如果你试图用不同的返回类型来实现它,编译器会抱怨。这是否意味着如果我们使用 lamda 来实现,规则会有一些变化?

标签: java lambda java-8 functional-interface


【解决方案1】:

因为你也可以写

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

这是你在使用 lambda 表示时最终会做的事情

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

【讨论】:

  • 谢谢,但上面的实现会显示编译错误-'无效方法不能返回值'。请检查。
  • @vinod 注意,我没有在代码中添加return,因此它应该可以成功编译。
猜你喜欢
  • 2016-02-01
  • 2016-04-12
  • 2014-04-18
  • 2011-08-26
  • 2012-05-08
  • 1970-01-01
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多