[英]Why can I use the same lambda for Runnable and Supplier Functional Interfaces?
取下一段代码
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
}
另外,下面我明白了java为什么以及如何区分这两个
Runnable a = this::test;
Runnable b = this::testInt;
void test() {
counter++;
}
int testInt() {
return counter++;
}
那么为什么第一个代码片段中带有 b 的行没有编译错误? 或者我应该说java如何知道将return语句放在哪里? 是不是只看函数式接口方法的方法签名?
是不是只看函数式接口方法的方法签名?
这个。 Java 注意到 lambda 被分配给一个Runnable
并推断不应该有return
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.