Issues with pattern variables inside Enum
Gavin Bierman
gavin.bierman at oracle.com
Wed Oct 13 13:09:49 UTC 2021
Hi Francois,
> On 6 Oct 2021, at 00:04, Francois Green <francois.green at gmail.com> wrote:
>
> I don't know if it should, but this works:
>
> public class PatNum {
>
> public static void main(String[] args) {
>
> enum Suit {
> Heart("♡"), Club("♣"), Spade("♠"), Diamond("♢");
>
> String symbol;
>
> Suit(String symbol) {
> this.symbol = symbol;
> }
>
> public String color() {
> return switch(this) {
> case Club, Spade -> "Black";
> case Diamond, Heart -> "Red";
> };
> }
> }
>
> for (var suit : Suit.values()) System.out.println(suit.color());
> }
> }
>
Yes, that is correct - you are using enum constants as switch labels in a switch expression. All good.
>
>
> Trying to use a pattern variable causes an error:
>
> public class PatNum {
>
> public static void main(String[] args) {
>
> enum Suit {
> Heart("♡"), Club("♣"), Spade("♠"), Diamond("♢");
>
> String symbol;
>
> Suit(String symbol) {
> this.symbol = symbol;
> }
>
> public String color() {
> return switch(this) {
> case Club c -> "Red";
> case Spade s -> "Black";
> case Diamond d -> "Red";
> case Heart h -> "Red";
> };
> }
> }
>
> for (var suit : Suit.values()) System.out.println(suit.color());
> }
> }
>
> PatNum.java:16: error: cannot find symbol
> case Club c -> "Red";
> ^
> symbol: class Club
> location: class Suit
> PatNum.java:17: error: cannot find symbol
> case Spade s -> "Black";
> ^
> symbol: class Spade
> location: class Suit
> PatNum.java:18: error: cannot find symbol
> case Diamond d -> "Red";
> ^
> symbol: class Diamond
> location: class Suit
> PatNum.java:19: error: cannot find symbol
> case Heart h -> "Red";
> ^
> symbol: class Heart
> location: class Suit
> Note: PatNum.java uses preview features of Java SE 17.
> Note: Recompile with -Xlint:preview for details.
> 4 errors
> error: compilation failed
I’m afraid that *is* an error. This preview feature only allows type patterns to appear as switch labels. You have written, e.g. Club c, but Club is not a type, it’s an enum constant; so the compiler correctly complains.
Gavin
More information about the amber-dev
mailing list