Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically convert if-else if statement to switch

Is there a hot key or easy way to replace an if-else if statement with a switch in IntelliJ? I would prefer not to manually convert the if-else if statement to a switch. I am looking to be able to highlight the if-else if statement and press a combination of keys or use a menu button.

like image 706
Daiwik Daarun Avatar asked Feb 01 '15 03:02

Daiwik Daarun


People also ask

Can you always convert an IF statement to a switch statement?

You can always convert an if statement to a switch statement. The break keyword must be used in a switch statement; otherwise, a syntax error occurs. The default case must be specified in a switch statement.

How do you use if else and switch together?

The if-else statement is used to choose between two options, but the switch case statement is used to choose between numerous options. If the condition inside the if block is false, the statement inside the else block is executed. If the condition inside the switch statement is false, the default statements are run.

Can a switch statement be replaced by multiple IF ELSE statement?

A switch statement can replace multiple if checks. It gives a more descriptive way to compare a value with multiple variants.


Video Answer


5 Answers

Update: as @christopheml pointed out in comments on another answer, "Replace If with Switch" seems to have disappeared in IntelliJ 2018.1. A bug has been filed here.


There are IntelliJ intentions named "Replace If with Switch" and "Replace Switch with If". Check your preferences to see if those options are enabled. If so, I would expect that you would see a quickfix option (Option+Enter on Mac, Alt+Enter on Windows) whenever IntelliJ can automatically handle the conversion from one to the other.

like image 104
stkent Avatar answered Oct 04 '22 11:10

stkent


I just found out that you have to click on the first if, wait for the light bulb icon to appear and then choose Replace if with Switch.

like image 20
Henrique de Sousa Avatar answered Oct 04 '22 12:10

Henrique de Sousa


Android studio (intelliJ idea):

Put your cursor on the switch/if statement and:

mac: option + return

win: alt + enter

like image 22
Oded Breiner Avatar answered Oct 04 '22 11:10

Oded Breiner


Checkout settings enter image description here

  • Minimum number of 'if' conditions branches: 3
  • Only suggest on null-safe expressions
like image 30
kreker Avatar answered Oct 04 '22 11:10

kreker


If it doesn't offer the replacement anymore, its probably because disabled feature on "Intentions". (Android studio (IntelliJ))

Solution is simple:

  • File > Settings > Editor > Intentions - Search: "replace switch"

or

  • File > Settings - Search: "replace switch" > Editor > Intentions

and check the blank checkbox

like image 26
zgr Avatar answered Oct 04 '22 13:10

zgr