Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant expression required error in switch statement with strings [duplicate]

I get a JSON response which roughly looks like this.

{
  "status": "success",
  "data": [
    {
      ....
    }
  ]
}

The status field can have two values: success or fail.

So in my code, I have the following enum.

private enum Status {
    SUCCESS("success", 0),
    FAIL("fail", 1);

    private String stringValue;
    private int intValue;
    private Status(String toString, int value) {
        stringValue = toString;
        intValue = value;
    }

    @Override
    public String toString() {
        return stringValue;
    }
}

What I want to do is in a switch statement, I need to check for the status value and execute code in each condition.

String status = jsonObj.getString("status");

switch (status) {
    case Status.SUCCESS.toString():
        Log.d(LOG_TAG, "Response is successful!");
    case Status.FAIL.toString():
        Log.d(LOG_TAG, "Response failed :(");
    default:
        return;
}

But I get the Constant expression required error at each case.

I checked the value returned by Status.SUCCESS.toString() and Status.FAIL.toString() which indeed return strings.

Any idea why this error still occur?

like image 609
Isuru Avatar asked Aug 10 '15 09:08

Isuru


People also ask

Can we use constants in switch case?

The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

How do you solve a constant expression required error in C++?

For example, if a program requires a “const”, but you're feeding it a “variable value”, which can be changed in the program or overwritten. So, use the keyword “const” before that variable to make it a constant and resolve the error.

Can a string control a switch statement?

Strings in switchIt is recommended to use String values in a switch statement if the data you are dealing with is also Strings. The expression in the switch cases must not be null else, a NullPointerException is thrown (Run-time). Comparison of Strings in switch statement is case sensitive.

What is the meaning of error constant expression required?

This error has the following causes and solutions: You tried to initialize a constant with a variable, an instance of a user-defined type, an object, or the return value of a function call.


1 Answers

case statements have to be compile-time evaluable.

Something like Status.SUCCESS.toString() doesn't satisfy that. A string literal, on the other hand, does.

The obvious fix is to use an an if block.

like image 94
Bathsheba Avatar answered Sep 30 '22 08:09

Bathsheba