java—为什么我可以对可运行接口和供应商功能接口使用相同的lambda?

ioekq8ef  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(256)

接受下一段代码

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语句放在哪里?只是通过查看函数接口方法的方法签名吗?

1aaf6o9v

1aaf6o9v1#

只是通过查看函数接口方法的方法签名吗?
这个。java注意到lambda被分配给 Runnable 并推断不应该有 return .

相关问题