11

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?

Isuru
  • 30,617
  • 60
  • 187
  • 303

1 Answers1

33

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483