Hello, Guy!
I think, the same problem was already solved when we differentiate
between switch expression and switch statement. In particular, this
syntax is invalid:
switch (0) {
default -> {
yield " foo ";
}
}.trim();
You must parenthesize the qualifier:
(switch (0) {
default -> {
yield " foo ";
}
}).trim();
The same should be done with the proposed do-expression:
(do { blah blah blah;
if (p) yield myCollection;
blah blah blah;
yield otherCollection;
}).add(x);
This allows to syntactically separate do-expression and do-while statement.
With best regards,
Tagir Valeev
On Tue, Mar 24, 2020 at 10:00 AM Guy Steele <[email protected]> wrote:
>
> There are many ways to invent a syntax for embedding a block within an
> expression (gcc allows a block to appear within immediately enclosing
> parentheses), but using the “do” keyword could be problematic within Java
> because in principle there could be some confusion with the “do { … }
> while(x)” statement. Consider the statement:
>
> do { blah blah blah;
> if (p) yield myCollection;
> blah blah blah;
> yield otherCollection;
> }.add(x);
>
> It sure looks like a loop until you get to that last line and realize it’s
> really an expression statement.
>
> —Guy
>
> On Mar 23, 2020, at 10:23 PM, Tagir Valeev <[email protected]> wrote:
>
> Hello!
>
> Now we have a legal way to execute several statements within an expression,
> yielding the result with a yield statement. This could be done via `switch`
> expression.
>
> Sometimes it's desired to do this without any switch. One may abuse the
> switch expression feature writing `switch(0) { default -> { ... code block
> ending with 'yield' }}`.
>
> How about creating a special syntax for such kind of expression. It could
> look like `do { ... code block ending with 'yield' }`?
>
> E.g. consider:
>
> class X {
> static final String field;
>
> // now we are forced to split field declaration and initialization
> // also initializer could be long and it could be not evident that its main
> purpose
> // is to initialize the field
> static {
> try {
> field = initializeField();
> }
> catch(CheckedException e) {
> throw new RuntimeException(e);
> }
> }
> }
>
> Since Java 14 we can write
>
> class X {
> // field declaration and initialization in the same place: easier to
> navigate through code
> // though we are abusing the switch expression
> static final String field = switch(0) { default -> {
> try {
> yield initializeField();
> }
> catch(CheckedException e) {
> throw new RuntimeException(e);
> }
> }};
> }
>
> It could be like
>
> class X {
> // concise syntax. Now we know that the main block purpose
> // is to initialize the field
> static final String field = do {
> try {
> yield initializeField();
> }
> catch(CheckedException e) {
> throw new RuntimeException(e);
> }
> };
> }
>
> It's similar to Perl 'do BLOCK' expression
> https://perldoc.perl.org/functions/do.html
>
> What do you think?
>
> With best regards,
> Tagir Valeev
>
>