3

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?

Naboki
  • 85
  • 1
  • 5

1 Answers1

4

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:
     ...
Joni
  • 108,737
  • 14
  • 143
  • 193
  • Okay, I understand the first part. But if I change `int test` to `Cons test`, `test` is not longer an integer. So why should I compare a Cons-Object with integer and how can I even initialize a enum-object? Your second point: i don't know how to use `Cons lookUpByVal(int test) { ... }` in code. I copied your code and got multiple syntax errors :d – Naboki Mar 27 '20 at 22:07
  • You don't initialize Cons objects. They already exist: they are Cons.ONE and Cons.TWO. As to the second point: You can write for example `if (test==1) return Cons.ONE; if (test==2) return Cons.TWO` You can get fancier by using lists or maps or other data structures. – Joni Mar 27 '20 at 22:24