groovy-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From fo...@univ-mlv.fr
Subject Re: [GEP] Switch expressions syntax from Java 11 or 12 (perhaps)
Date Fri, 09 Mar 2018 20:48:08 GMT
----- Mail original -----
> De: "MG" <mgbiz@arscreat.com>
> À: "dev" <dev@groovy.apache.org>, "Remi Forax" <forax@univ-mlv.fr>
> Envoyé: Jeudi 8 Mars 2018 23:55:11
> Objet: Re: [GEP] Switch expressions syntax from Java 11 or 12 (perhaps)

> Hi Remi,
> 
> I have used Groovy exclusively for the last years, so not really used to
> Java lambdas, but why can't you use something along the line of:
> 
> int result = switch (s) {
>     case "Foo" -> 1;
>     case "Bar" -> 2;
>     case default -> (System.out.println("Neither Foo nor Bar,
> hmmm...");  3; )
> }
> 
> or
> 
> int result = switch (s) {
>     case "Foo" -> 1;
>     case "Bar" -> 2;
>     case PATTERN_ANY -> { System.out.println("Neither Foo nor Bar,
> hmmm...");  3; }
> }
> 
> etc ?

in a lambda in Java, you can not modify a local variable declared outside of the lambda,
by example
  int i = 0;
  Runnable r = () -> { i++; };
does not compile.

The idea behind is the compiler needs to expand the liveness of 'i' to be accessible outside
the code that declare 'i' and this is only allowed if 'i' do not change its value.
This restriction is important because it means the JIT can create the lambda whenever it wants
and not necessarily when the user declare it (note: the JIT already does that for any other
expressions that why we wanted to keep that capability).   

but in a switch, you can not delay the creation of a case (technically you can because you
can always do weird thing but, it's not what people will expect),
so disallowing
  int i = 0; 
  switch(foo) {
    case 0 -> { i++; }
  }
make little sense.

> 
> I am in the "never liked break camp", so I also would not want to see
> its use elevated... ;-)

i agree, that's the wrong message.

> Cheers,
> mg

regards,
Rémi

> 
> 
> On 08.03.2018 20:52, Remi Forax wrote:
>>
>>>> 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.
>> yes, you can not use the normal break/containue inside an expression,
>> so break foo; in an expression switch has only one meaning.
>>
>>> 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.
>> using break here is ugly, i agree with you but we (the amber EG) are not able to
>> find a better solution,
>> if you know a better way to handle local return of a value in the case of a
>> switch, please help us.
>>

Mime
View raw message