After upgrading to Java 21, I realized that the promised switch expression has several surprising properties. The most surprising part is the yield
keyword which must be inserted if a block is used in a branch. Like in
int x = switch (y) {
...
case 7 -> {
assert ...;
8; // this is not allowed; a yield must be added in front
}
};
While digging for a reason, I found JEP 354 which apparently introduced the syntax. Now, the obscure part is, that the very last paragraph of that documents indicates that such a move would be a bad idea. Are there any insights, why this contradiction was ignored and the yield
syntax was introduced? Are there any reasons that would prevent using either a break expr syntax or having expressions at the end of a block in that context as a result?
break expr
seems to conflict with ordinary labelled break statements, so if anything it's more surprising that it made it into JEP 325 than that it wasn't used in the end. $\endgroup$