0

I want to use global constants in a switch statement. I wrote the constants in a Singleton called ColorManager in this way

public static final int blue = 3;
public static final int red = 5;
public static final int black = 7;

in my HomeActivity I wrote this code

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    ColorManager cm = ColorManager.getInstance(this);
    switch (requestCode) {
        case cm.blue: {
        }
        case cm.red: {
        }
        case cm.black: {
        }
    }
}

But I get an error in the switch statement:

Constant expression required

The values are final so constant, I don't understand why I get this error. I found similar topics but in all cases the properties was not declared as final.

Sufian
  • 6,405
  • 16
  • 66
  • 120
kev.a
  • 33
  • 1
  • 6

3 Answers3

3

It will compile if you access your static final fields statically; e.g. case ColorManager.blue:. If you try and access then from a variable cm, then you're preventing the compiler recognising them as compile-time constants.

khelwood
  • 55,782
  • 14
  • 81
  • 108
0

Use ClassName.variable i.e ColorManager.red

Shuddh
  • 1,920
  • 2
  • 19
  • 30
0

Try this code

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

    switch (requestCode) {
        case ColorManager.blue: {
        }
        case ColorManager.red: {
        }
        case ColorManager.black: {
        }
    }
}
FBRNugroho
  • 710
  • 6
  • 8