【发布时间】: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