This morning I was refactoring some of my code to get rid of nested FOR loops and all of the sudden run into this compile time error. Here’s the mocked code:
public void doSomething(int i, int j) {
switch(Position.getPosition(i, j)) {
case Position.TOP:
// do something
break;
case Position.MID:
// do something
break;
case Position.BTT:
// do something
break;
}
}
enum Position {
TOP, MID, BTT, NONE;
public static Position getPosition(int idx, int lastIdx) {
if ( idx == 0)
return TOP;
else if ( idx < lastIdx)
return MID;
else if ( idx == lastIdx)
return BTT;
else
return NONE;
}
}
Turned out that in this particular case (enum constants as SWITCH selectors) one has to omit qualifiers for SWITCH to work. Totally counterintuitive since, for example in IF statement you actually need a qualifier. The best explanation I found - this is done deliberately so you will not be able to use some other enum constants in the same switch (dah?).
Anyway - below is fixed code that will work (case Position.TOP is changed to case TOP:)
public void doSomething(int i, int j) {
switch(Position.getPosition(i, j)) {
case TOP:
// do something
break;
case MID:
// do something
break;
case BTT:
// do something
break;
}
}
enum Position {
TOP, MID, BTT, NONE;
public static Position getPosition(int idx, int lastIdx) {
if ( idx == 0)
return TOP;
else if ( idx < lastIdx)
return MID;
else if ( idx == lastIdx)
return BTT;
else
return NONE;
}
}
Thanks, this was handy!