Switch labels (null again), some tweaking

Brian Goetz brian.goetz at oracle.com
Fri Mar 12 14:12:21 UTC 2021

The JEP has some examples of how the `null` case label can combine with 
others.  But I would like to propose a more general way to describe 
what's going on. This doesn't change the proposed language (much), as 
much as describing/specifying it in a more general way.

We have the following kinds of switch labels:

     case <constant>
     case null
     case <pattern>

The question is, which can be combined with each other into a single 
case, such as:

     case 3, null, 5:

This question is related to, which can fall into each other:

     case 3:
     case null:
     case 5:

We can say that certain labels are compatible with certain others, and 
ones that are compatible can be combined / are candidates for 
fallthrough, by defining a compatibility predicate:

  - All <constant> case labels are compatible with each other;
  - The `null` label is compatible with <constant> labels;
  - The `null` label is compatible with `default`;
  - The `null` label is compatible with (explicit) type patterns:

(There is already a check that each label is applicable to the type of 
the target.)

Then we say: you can combine N case labels as long as they are all 
compatible with each other.  Combination includes both comma-separated 
lists in one case, as well as when one case is _reachable_ from another 
(fall through.)  And the two can be combined:

     case 3, 4: // fall through
     case null:

So the following are allowed:

     case 1, 2, 3, null:

     case null, 1, 2, 3:

     case null, Object o:

     case Object o, null:

     case null, default:    // special syntax rule for combining default

The following special rules apply:

  - `default` can be used as a case label when combined with compatible 
case labels (see last example above);
  - When `null` combines with a type pattern, the binding variable of 
the type pattern can bind null.

The semantics outlined in Gavin's JEP are unchanged; this is just a new 
and less fussy way to describe the behavior of the null label / specify 
the interaction with fallthrough.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20210312/6121baa0/attachment.htm>

More information about the amber-spec-experts mailing list