New JEP: Switch Expressions for the Java Language

Brian Goetz brian.goetz at
Sun Dec 10 19:40:30 UTC 2017

> Otherwise doing a side effect inside of the switch,
>   int a = 3;
>   switch(f(a = 4)) {
>       case L -> a; 
>   }
> and you're in trouble.

That’s implicitly choice (c) — “anything goes.”  I think it is reasonable to restrict side-effects on locals — were we designing conditional expressions today, we’d probably choose that too.  If we outlaw such mutations, then such trouble can’t happen.  

> Your talking about semantics consistency in general, it's not what a regular user see, the "syntax to semantics" consistency is more important,
> if the syntax use an arrow, then the semantics should be the same with the other(s) construct(s) that are using an arrow.  

This is a good general principle, and among other things it means we should choose a syntax that is evocative of what we want to mean (which we’re not fully decided on yet).  If what we mean is “anything goes”, then maybe what we should conclude is that -> is a bad choice.  (We certainly have “justified” the uncomfortable ambiguity between local and nonlocal return by comparison with lambdas).  I think all such choices are provisional until we’ve worked out both what we want to have happen, and a sensible way to express it, and then ask ourselves if we’re asking too much (both semantically and syntactically) of users.  But lets not let the tail wag the dog.

So, speaking semantically only:
 - We should not allow fall through in expression switch; I don’t think it makes any sense.  
 - I’m pretty convinced that nonlocal returns out of expression switch (other than throwing) is similarly a wrong fit.  (We allow this in neither conditional expressions nor lambdas.)
 - Switch expressions should definitely be able to reference locals, but we’re open minded to some restrictions (such as no mutation). 
 - We could justify allowing switch expressions to mutate locals, since other expressions can too, but we could similarly justify restricting mutation
 - More strongly, we could justify restricting even referencing non-eff-final locals, though this is starting to get onto thin ice, because the only argument we have for this is “for (superficial) consistency with lambdas”, which is pretty weak.

> and there are several arguments against 2, as you wrote, "it's unlike anything else", it forces users to think where the capture occurs exactly (my example above) and it's not "syntax to semantics" consistent but this can be fixed by not using the arrow symbol.

If mutation is restricted (which I think is really the first question), then there’s no confusion about "where the capture happens”.  So perhaps we should examine the basis on which we are willing to justify restricting mutation.  

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the amber-spec-experts mailing list