Constant expression required in switch statements

166 Views Asked by At

have this enum file containing some information:

public enum Constants {
    AGED_BRIE("Aged Brie");

    private final String label;

    Constants(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }
}

this Item class:

public class Item {
    public String name;

    public Item(String name) {
        this.name = name;
    }
}

and this factory method:

public class Factory {

    public void try(Item item) {
        String brie = Constants.AGED_BRIE.getLabel(); // contains "Aged Brie"
        switch (item.name) {
            case brie -> System.out.println("Hello World"); // Constant expression required
            // other cases ...
        }
    }
}

Unfortunately I get:

Constant expression required

and IntelliJ highlights case label statement.

  • What am I missing?
1

There are 1 best solutions below

5
Elliott Frisch On

You can't have a method named try. You need your case(s) to expand to constants. You shouldn't make fields public. But let's start by making Constants into Cheese. Like,

public enum Cheese {
    CHEDDAR("Cheddar"), AGED_BRIE("Aged Brie");

    private final String label;

    Cheese(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }
}

Now in Item, instead of String(s) we want to use the enum type so you have something to match on in constant expressions later. Not changing Constants would have made this confusing. Like,

public class Item {
    private Cheese cheese;

    public Item(Cheese cheese) {
        this.cheese = cheese;
    }

    public Cheese getCheese() {
        return cheese;
    }
}

Now, we can actually use that for our case(s). It's a Factory. We can make things. Like,

public void make(Item item) {
    switch (item.getCheese()) {
    case AGED_BRIE -> System.out.println("Aged Brie");
    case CHEDDAR -> System.out.println("Cheddar");
    }
}