if/else if to switch statement

For some reason I think I remember using an IntelliJ intention that converted a long if/else if block to a switch statement. However, I can't seem to get it to trigger now.

Am I just being delusional or does this really exist?

0
9 comments

When it is possible to convert an if to a switch the intention should appear on the if keyword. This intention is part of the bundled Intention Power Pack plugin, so you may want to check if that is enabled.

Bas

0

Also, make sure your if/else if statements evaluate a variable, not a method. For instance if you use this, IntelliJ won't suggest a refactoring to switch case:

if(getValue() == 1){
} else if(getValue() == 2){
} else if(getValue() == 3){
}

However, if you have this it will work:

int value = getValue();
if(value == 1){
} else if(value == 2){
} else if(value == 3){
}

0

Also note that you won't be able to convert an if statement when you are using the tripple equal (===) operator. 

0

It does not convert if/else if to switch, if the value tested is an enum. / using 2016.3.1

0

Could you please provide code example?

0
import org.apache.zookeeper.KeeperException;

try
{
tryCreate();
} catch (KeeperException first) {
if (first.code() == KeeperException.Code.NODEEXISTS) {
System.out.println("nodeexists");
} else if (first.code() == KeeperException.Code.NONODE) {
System.out.println("nonode");
} else {
System.out.println("hmm");
}
}
0

Seems the problem is that "KeeperException.Code.NODEEXISTS" is not a constant: https://youtrack.jetbrains.com/issue/IDEA-163129

0

It is an enum value. What do you mean by constant btw?

0

Sorry, looks like a bug. Reported issue on YouTrack: https://youtrack.jetbrains.com/issue/IDEA-165458

1

Please sign in to leave a comment.