[External] : Re: Rehabilitating switch -- a scorecard

forax at univ-mlv.fr forax at univ-mlv.fr
Wed May 19 09:57:36 UTC 2021

----- Mail original -----
> De: "Brian Goetz" <brian.goetz at oracle.com>
> À: "Remi Forax" <forax at univ-mlv.fr>
> Cc: "John Rose" <john.r.rose at oracle.com>, "amber-spec-experts" <amber-spec-experts at openjdk.java.net>
> Envoyé: Mardi 18 Mai 2021 19:07:41
> Objet: Re: [External] : Re: Rehabilitating switch -- a scorecard

>> to fill the gap, we need
>>   - _ as pattern equivalent to var _ + _ not be entered in the scope
> On the list, will come at some point.
>>   - constant as pattern, Foo(constant) being equivalent to Foo(var x) && x ==
>>   constant
> Maybe, not sure it carries its weight.

The problem of using guards for constants instead of having a constant pattern introduces a weird asymmetry when you have all the constants are total.

By example
  enum Color { RED, BLUE }
  record Car(Color color) {}

This switch is total
  switch(color) {
    case RED: ...
    case BLUE: ...

This one is not total
  switch(car) {
    case Car(color) && color == Color.RED: ...
    case Car(color) && color == Color.BLUE: ...

so it needs a default or at least Car(var color). Introducing a new enum value will not be detected by the compiler.

If we add a constant pattern then this switch is total
  switch(car) {
    case Car(Color.RED): ...
    case Car(Color.BLUE): ...
And if we add target typing so when the compiler sees Car(UNKONWN) it tries to see if Color is not an Enum and Enum.UNKNOWN exists
(to have the same behavior as a switch on an enum)

We can write
  switch(car) {
    case Car(RED): ...
    case Car(BLUE): ...



More information about the amber-spec-experts mailing list