yield in code blocks
Pablo Grisafi
pablogrisafi1975 at gmail.com
Wed Dec 13 14:38:27 UTC 2023
Recently in in the Effect cases in switch proposal Brian Goetz said
the new switch can be used
as a replacement for block expressions, writing something like
```
var x = switch (0) {
default -> {
String[] choices = new String[2];
var choice0 = f(0)
choices[0] = choice0;
choices[1] = f(1, choice0);
yield choices;
}
}
```
(I slightly changed the original code to make the block more necessary)
I wonder if Java could, as a small improvement, allow yield in any
code block, so we could write
```
var x = {
String[] choices = new String[2];
var choice0 = f(0)
choices[0] = choice0;
choices[1] = f(1, choice0);
yield choices;
}
```
Java already has blocks, and are almost never used, I suspect because
you can't return a value from a block.
They are a nice addition to the language, they are somewhere between a
local function and a formatting option,
they let you have restricted scope local variables which are only
needed as intermediate values in the computation,
neatly hidden from the rest of the program.
I'm just suggesting to generalize the use of yield as a local return
The complete Goetz quote:
> A more controversial use of the new-and-improved switch is as a
> replacement for
> block expressions. Sometimes we want to use an expression (such as when
> passing
> a parameter to a method), but the value can only be constructed using
> statements:
> ```
> String[] choices = new String[2];
> choices[0] = f(0);
> choices[1] = f(1);
> m(choices);
> ```
> While it is somewhat "off label", we can replace this with a switch
> expression:
> ```
> m(switch (0) {
> default -> {
> String[] choices = new String[2];
> choices[0] = f(0);
> choices[1] = f(1);
> yield choices;
> }
> })
> ```
Pablo Grisafi
pablogrisafi1975 at gmail.com
More information about the amber-spec-observers
mailing list