[英]Why can I use the same lambda for Runnable and Supplier Functional Interfaces?
Take the next piece of code取下一段代码
private static int counter = 0;
void some method() {
Runnable a = () -> 1; // compilation error -> Bad return type - which is expected
Runnable b = () -> counter++; // Here I am expecting to receive an error
Supplier<Integer> c = () -> counter++; // this works - as expected
}
Also, below I understand why and how java differentiates between the 2另外,下面我明白了java为什么以及如何区分这两个
Runnable a = this::test;
Runnable b = this::testInt;
void test() {
counter++;
}
int testInt() {
return counter++;
}
So why is there no compilation error on the line with b from the first code snippet?那么为什么第一个代码片段中带有 b 的行没有编译错误? Or should i say how java knows where to put the return statement?
或者我应该说java如何知道将return语句放在哪里? Is it just by looking at the method signature of the functional interface method?
是不是只看函数式接口方法的方法签名?
Is it just by looking at the method signature of the functional interface method?
是不是只看函数式接口方法的方法签名?
This.这个。 Java notices that the lambda is being assigned to a
Runnable
and infers that there should not be a return
. Java 注意到 lambda 被分配给一个
Runnable
并推断不应该有return
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.