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?
Originally, when switch expressions were introduced in JEP 325, it was proposed that
break
should be used to yield a value.It was changed to
yield
in JEP 354. It was mentioned that:Which could be seen as a reason for the change. Using
return
for this certainly would not "facilitate easy disambiguation between switch statements and switch expressions", since you can alsoreturn
in switch statements.Then, in JEP 361, it was further explained that overloading
break
was "confusing".I would imagine overloading
return
would also be "confusing".Being able to return from a lambda expression isn't exactly "overloading"
return
in the same sense. The bodies of lambda expressions represent function bodies. It would make sense forreturn
to return from functions. The body of a switch expression, isn't a function.