kev.a
kev.a

Reputation: 33

Constant expression required in switch statement

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.

Upvotes: 0

Views: 7644

Answers (3)

FBRNugroho
FBRNugroho

Reputation: 710

Try this code

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

    switch (requestCode) {
        case ColorManager.blue: {
        }
        case ColorManager.red: {
        }
        case ColorManager.black: {
        }
    }
}

Upvotes: 0

Shuddh
Shuddh

Reputation: 1970

Use ClassName.variable i.e ColorManager.red

Upvotes: 0

khelwood
khelwood

Reputation: 59185

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.

Upvotes: 3

Related Questions