Why can't I use enums for switch-case-statements?

Viewed 1334

I want to use enum-constants for switch-case-statements.

I am using following enum/class:

public enum Cons {

  ONE(1), 
  TWO(2);

  private final int val;

  private Cons(final int newVal) {
    val = newVal;
  }

  public int getVal() {
    return val;
  }
}



public class Main {

  public static void main(String[] args) {

    int test;

    // some code

    switch(test) {
        case Cons.ONE.getVal():
            // ...
            break;
        case Cons.TWO.getVal(): 
            // ...
            break;
        default:
            // ...
    }
  }
}

Problem: "the case expression must be constant expression" => the values of my enum aren't constants, although the attribute private final int val is declared as final.

How can I use this enum for case-statements?

1 Answers

Case labels have to be compile time constant expressions. A method call is not one of those.

What you can do is change test into a Cons. Then you can use it in switch:

Cons test;

// some code

switch(test) {
    case Cons.ONE:
        // ...
        break;
    case Cons.TWO: 
        // ...
        break;
    default:
        // ...
}

If you must work with an int, create a method that returns the correct enum instance using the value.

Cons lookUpByVal(int test) { ... }

switch(lookUpByVal(test)) {
     case Cons.ONE:
     ...
Related