Amit Yadav
Amit Yadav

Reputation: 35114

Java called method return value as a switch case value

I have to use a value, typically return via a method in switch case.

int getVal(){return 121;}

 switch(expr){

    case getVal():
 }

But its giving comilation error: constant expression required.

I also tried like,

int _val = getVal();

 switch(expr){

    case _val:
 }

Having same result.

Is there any workaround to implement it.

Thanks, Amit

Upvotes: 4

Views: 2814

Answers (2)

Edwin Buck
Edwin Buck

Reputation: 70959

This won't work, because while you think that your method will effectively be a constant, it could be hidden, the class could be sub-classed, or any number of other items could interfere.

While the compiler could attempt to discern that the return value is a constant, it won't because it also doesn't have the whole picture as classes in a Java project can be compiled at different times (subclasses compiled after their parents, etc.)

Also it is not clearly established what a function as a switch label means. While you might see it as a shorthand for renaming a constant, someone else might expect it to be evaluated each time the switch was entered, while someone else might expect it to be evaluated each time the label was entered, and yet another might expect it to be evaluated each time the switch jumped to that label (which is impossible because you have to evaluate such a label prior to jumping to it.) Since there is no clear consensus, better to leave it out of the language until there is a clear consensus.

And that's not even getting into the assurance that such a method doesn't return a duplicate label (switches don't support multiple labels of the same value).

Upvotes: 0

SLaks
SLaks

Reputation: 888177

As the error clearly states, switch only works with constant expressions.

You need to use an if.

Upvotes: 6

Related Questions