groovy-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jochen Theodorou <blackd...@gmx.org>
Subject Re: [GEP] Switch expressions syntax from Java 11 or 12 (perhaps)
Date Thu, 08 Mar 2018 18:51:57 GMT
On 08.03.2018 17:34, Remi Forax wrote:
[...]
>>> 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.

you mean I cannot use the normal break/continue inside an expression 
switch, because this example

> int result = switch (s) {
>     case "Foo" -> 1;
>     case "Bar" -> 2;
>     default:
>         System.out.println("Neither Foo nor Bar, hmmm...");
>         break 3;
> }

is straight from the JEP 325 page. And that was actually my point, this 
overlap, but redefinition of break. break is what makes the switch-case 
ugly for most people in the first place. Giving that special treatment 
like this looks off to me.

>> 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.

A problem you would not have in Groovy, because we donĀ“t do the 
capturing like Java.

> 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.

maybe, but I still think it does not make so much sense on its own. With 
a step-by-step approach of getting features in I can understand this, 
but then it means to decide to use this here, before deciding the 
details of pattern matching... and that sounds wrong

bye Jochen

Mime
View raw message