groovy-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Remi Forax <fo...@univ-mlv.fr>
Subject Re: [GEP] Switch expressions syntax from Java 11 or 12 (perhaps)
Date Thu, 08 Mar 2018 16:34:19 GMT
Hi Jochen,

----- Mail original -----
> De: "Jochen Theodorou" <blackdrag@gmx.org>
> À: "dev" <dev@groovy.apache.org>
> Envoyé: Vendredi 2 Mars 2018 00:57:16
> Objet: Re: [GEP] Switch expressions syntax from Java 11 or 12 (perhaps)

> On 01.03.2018 16:39, Jesper Steen Møller wrote:
> [...]
>> |int numLetters = switch (day) { case MONDAY, FRIDAY, SUNDAY -> 6; case
>> TUESDAY -> 7; case THURSDAY, SATURDAY -> 8; case WEDNESDAY -> 9; };|
>> 
>> with
>> 
>> |case LABEL -> expression;|
>> 
>> essentially sugar for
>> 
>> |case LABEL: break expression;|
> 
> to make this straight.
> 
>> int result = switch (s) {
>>     case "Foo":
>>         break 1;
>>     case "Bar":
>>         break 2;
>>     default:
>>         System.out.println("Neither Foo nor Bar, hmmm...");
>>         break 3;
>> }
> 
> is the long form of
> 
>> int result = switch (s) {
>>     case "Foo" ->  1;
>>     case "Bar" ->  2;
>>     default:
>>         System.out.println("Neither Foo nor Bar, hmmm...");
>>         break 3;
>> }
> 
> The default here has no shorter version, because they are using a
> statement and need to return something in the expression. I understood
> the proposal, that both forms are valid and can be mixed.
> 
> There is a few things I dislike...and most of all it is the break
> command here.
> 
>> int accumulator = 0
>> LOOP: for (T element : someList) {
>>   accumulator += switch (element.type) {
>>     case PLUS_ONE -> +1;
>>     case MINUS_ONE -> -1;
>>     case ERROR:
>>       break LOOP;
>>     case default -> 0
>>   }
>> }
> 
> with the idea that element.type is an enum... But my problem is with
> break LOOP. Is LOOP the label LOOP, or is it a constant/variable?

this will not compile, because you can not use return or break/continue inside an expression
switch.

> 
> If they need the break only to break out of the switch, then why not
> capitalize on lambdas ?

it was the first idea :)
but lambda can capture effectively final local variable, when a case in an expression switch
acts more like a routine so you can access any variables with no restriction. So re-using
the same syntax for two different semantics is not a good idea.

The idea is that the expression switch should be used when it's a simple switch and the C
switch with all it's subtle behaviors if the control flow is more complex, 
exactly like you use for(:) if it's a simple loop and for(;;) if it's a more complex one.
 

[...]

> 
> bye Jochen

cheers,
Rémi

Mime
View raw message