Java is called method return value as switch register value

I need to use the value usually returned using the method in the case of a switch.

int getVal(){return 121;} switch(expr){ case getVal(): } 

But its output is a compilation error: a constant expression is required.

I tried too

 int _val = getVal(); switch(expr){ case _val: } 

Having the same result.

Is there any way around this?

Thanks Amit

+4
source share
2 answers

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

You need to use if .

+6
source

This will not work, because while you think that your method will be effectively constant, it may be hidden, the class may be subclassed, or any number of other elements may interfere.

While the compiler may try to recognize that the return value is constant, it will not be because it also does not have the whole image, since classes in a Java project can be compiled at different times (subclasses compiled after their parents, etc.) d.)

It is also not clear what the function means as a switch label. Although you can see it as a shorthand for renaming a constant, someone can expect it to be evaluated every time a switch is entered, while someone can expect it to be evaluated every time a label is entered , and one more can expect this every time the switch jumps to this label (which is impossible, because you must evaluate such a label before switching to it). Since there is no clear consensus, it is best to leave it outside the language until a clear consensus appears.

And this does not even mean that such a method does not return a duplicate label (the switches do not support multiple labels of the same value).

0
source

Source: https://habr.com/ru/post/1412612/


All Articles