expression switch follow-ups

Brian Goetz brian.goetz at oracle.com
Tue Oct 23 19:54:10 UTC 2018



> First, a statement switch can use the arrow syntax with an expression that throw an expression.
>    switch(x) {
>      case 10 -> 42;
>      default -> throw new AssertionError();  // there is no curly braces needed here
>    }
> but lambdas do not allow throw as an expression.
> This is not coherent, i think, we should fill that hole by allowing throw expression with no curly braces in lambdas (like we already allow function calls that return void in a lambda).

General warning: let's be careful with "for consistency" arguments; in a 
language as complex and which has been maintained over 20+ years like 
Java, you will always find inconsistencies, and the cure may be worse 
than the disease.  (If "for consistency" is the best argument one can 
think of for a given idea, that's a sign that it's probably not such a 
strong idea.)

For example, the same "for consistency" argument could lead you down the 
slippery slope of allowing throw everywhere an expression is allowed, 
such as

     m(throw e) // never calls m()
or
     for (int i = throw e; i++; i<j) { ... }

which I think is farther than we'd want to go.  But, I think you are 
making an argument for a narrower form of consistency, which is 
"consistency after the arrow", as both constructs here attempt to 
provide a streamlined single-consequent, no-brace form?

(Note that we could also "restore consistency" by requiring the braces 
on the switch.)

That said, lambdas of the form

     () -> throw e;

do seem pretty harmless.


> A question that have came twice at the end of my both talks about the expression switch is: why there is not arrow syntax for the try-catch/try-finally/try-with-resources ?

(This is, in fact, an illustration of the general silliness of most "for 
consistency" arguments :)

I agree, this is a poor direction to go down.



More information about the amber-spec-experts mailing list