Search code examples
javaenums

Enum with constructor in switch-statement


It might be a silly question, but I can't understand why it doesn't work:

public class MainClass {

    public enum Header{
        ValueType("Value Type"),
        LimitType("Limit Type"),
        Currency("Currency");

        Header(String value) {
            this.value = value;
        }

        private final String value;

        public String getValue(){
            return value;
        }
    }

    static void getHeaderValue (String headerValue) {

        switch (headerValue) {
            case Header.LimitType.getValue() :
                System.out.println(Header.LimitType.getValue());
                break;
            case Header.ValueType.getValue() :
                System.out.println(Header.ValueType.getValue());
                break;
            case Header.Currency.getValue() :
                System.out.println(Header.Currency.getValue());
                break;
            default:
                break;
        }
    }
}

The compiler notices that

constant string expression required.

What's the reason for this error message?


Solution

  • Nothing to do with your enum but with your switch statement, which needs constants in its case clauses. case needs constant expressions like "helloWorld", the expression Header.LimitType.getValue() maybe returns a value that never changes, but it is not a constant expression to the compiler.