When a return statement occurs within a lambda expression, it simply causes a return from the lambda. It does not cause an enclosing method to return.
So, for switch expressions why the keyword yield
had introduced while return
keyword could have been used instead? The first return for returning from method and the inside one for return from switch statement.
class TestClass {
public int testMethod() {
// ...
int a = switch (allOptions) {
case "case1" -> {
System.out.println("case 1");
return 1;
}
default -> {
System.out.println("default");
return -1;
}
};
return a;
}
}
Consider this example for lambda expressions:
class TestClass {
interface FunctionalInterface {
int test(int n);
}
public int testMethod() {
FunctionalInterface f = (n) -> {
return n * 2;
};
return f.test(10);
}
}
Is there any special reason for that?
Why return keyword is confusing in first example and not confusing in the second one?