Assignment In Switch

Alex Buckley alex.buckley at oracle.com
Thu Jan 22 00:48:23 UTC 2015


This is a variant of local variable declarations in expressions: 
http://mail.openjdk.java.net/pipermail/compiler-dev/2015-January/009233.html

More broadly, see the proposal for "Block Expressions for Java" in 
Project Coin (Feb/Mar 2009): 
http://mail.openjdk.java.net/pipermail/coin-dev/

Of course there is no limit to the number of tiny language features that 
can be suggested, but this is not a language design list.

Alex

On 1/21/2015 4:36 PM, Jake Wharton wrote:
> Seeing the newly-added, assignment-free try-with-resources in JDK 9, I was
> reminded of a common nuisance regarding the switch statement.
>
> A common pattern is obtaining a value, performing the switch, and acting on
> the value in some way. Here's a trivial example:
>
> String protocol = getProtocol();
> switch (protocol) {
>    case "http": return 80;
>    case "https": return 443;
>    default: throw new IllegalStateException("Unknown protocol: " + protocol);
> }
>
> In this example we only use it in the default case, but you can imagine
> other examples which make use of it in the individual cases.
>
> Having parity in the option to use either a value or do an assignment in
> creating a switch block would be useful.
>
> switch (String protocol = getProtocol()) {
>    case "http": return 80;
>    case "https": return 443;
>    default: throw new IllegalStateException("Unknown protocol: " + protocol);
> }
>
> The extreme simplicity of this example serves only to trivialize the value
> of this change. It can be seen as a bit more useful when multiple switches
> (linear or nested) are used.
>
> switch (int flag = (value>> 0) & 0xFF) { .. }
> switch (int flag = (value>> 8) & 0xFF) { .. }
> switch (int flag = (value>>16) & 0xFF) { .. }
> switch (int flag = (value>>24) & 0xFF) { .. }
>
> A seemingly minor improvement, but there's a few wins here:
>   * Parity with the behavior of the try-with-resources block.
>   * Avoiding the local in the outer scope when it's only use is inside the
> switch. As mentioned before, multiple switches that are either written
> linearly or nested need to use explicit blocks or add arbitrary variance to
> their variable names.
>
> and playing Devil's advocate to myself:
>   * Relatively low-leverage change. Kills 1LOC in a bunch of places, but no
> new magically awesome behavior as try-with-resources brought.
>
> I think this would be a useful (albeit tiny) addition to ease a specific
> use case.
>


More information about the discuss mailing list