为什么我可以对 Runnable 和 Supplier 功能接口使用相同的 lambda?

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 为什么以及如何区分 2


Runnable a = this::test; 
Runnable b = this::testInt;

void test() {
  counter++;
} 

int testInt() {
  return counter++;
}

那么为什么第一个代码片段中b行没有编译错误呢?或者我应该说 java 如何知道将 return 语句放在哪里?是不是只看函数式接口方​​法的方法签名?

Is it just by looking at the method signature of the functional interface method?

这个。 Java 注意到 lambda 被分配给 Runnable 并推断不应该有 return.