Issue
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
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? Or should i say how java knows where to put the return statement? Is it just by looking at the method signature of the functional interface method?
Solution
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
.
Answered By - Louis Wasserman
Answer Checked By - Pedro (JavaFixing Volunteer)