How to automatically convert if-else if statement to switch

前端 未结 7 2368
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 15:23

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

相关标签:
7条回答
  • 2020-12-15 16:03

    Android studio (intelliJ idea):

    Put your cursor on the switch/if statement and:

    mac: option + return

    win: alt + enter

    0 讨论(0)
  • 2020-12-15 16:07

    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.

    0 讨论(0)
  • 2020-12-15 16:11
    1. Select by double clicking on switch keyword
    2. Left Suggestion bulb will appear.
    3. Click on suggestion to replace switch with if else.

    This works on android studio. It worked in my case

    0 讨论(0)
  • 2020-12-15 16:12

    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

    0 讨论(0)
  • 2020-12-15 16:22

    Checkout settings

    • Minimum number of 'if' conditions branches: 3
    • Only suggest on null-safe expressions
    0 讨论(0)
  • 2020-12-15 16:27

    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.

    0 讨论(0)
提交回复
热议问题