1

I want to use the following enum as reference in a switch case:

public final enum myEnum {
    VALUE1,
    VALUE2,
    VALUE2,
    ...
}

I searched the internet already quite some time, but found only examples where the enum is used in the switch statement and the case stament as argument. I want to use only the values of the enum as argument of the case statements, the switch argument is another variable. Something like this:

String otherVariable = "VALUE2";
switch (otherVariable) {
    case myEnum,VALUE1.toString():
        ...
        break;
    case myEnum,VALUE2.toString():
        ...
        break;
    default:
        ...
        break;

When I code this straight forward, I get an error "case expressions must be constant expressions". What am I doing wrong? How do I implement this?

Kind regards WolfiG

1 Answer 1

6

What you want is probably

String other = "VALUE2";

MyEnum myEnum = MyEnum.valueOf(other);
switch (myEnum) {
    case VALUE1:
    ...
    case VALUE2:
    ...
}

You can't use myEnum.toString() because it's a method call, which can create different results between calls (ie non-constant).

Sign up to request clarification or add additional context in comments.

3 Comments

Hi daniu, nope, this doesn't work. Now I get an error: "cannot convert from MyEnum to MyEnum. Maybe it is worth noting that the enum is declared as member of a class and I call the enum in a method of that class.
@WolfiG Sorry, had a typo in my case statements. I'm not sure what you mean by "member of a class"; an enum (such as MyEnum) is a class by itself basically, so you can only have an inner enum; or you can have a value of the enum as a member, which shouldn't really make a difference.
You are right about the inner enum. And I found the trick: as the case attributes you need to use VALUE1 instead of MyEnum.VALUE1. Maybe you adjust your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.