Question
Why doesn't IntelliJ IDEA convert an if/else chain like:
int x;
if (true) x = 5;
else if (false) x = 7;
else x = 9;
into the equivalent ternary expression:
int x = true ? 5 :
false ? 7 :
9;
Even though the inspection says it supports if/else chains?
Answer
IntelliJ IDEA's default behavior does not support converting an entire if/else chain to a ternary operator. For chains involving more than two outcomes, such as multiple if/else statements, a ternary conversion is not implemented directly. However, if you need a ternary operator to replace your if/else chain, especially in cases like:
int x = (color(sky) == blue) ? 5 :
(temp(sun) == hot) ? 7 :
9;
where conertion to ternary or switch expressions are not applicable, you can create a custom inspection in IntelliJ IDEA to achieve this.
Steps to Enable Custom Inspection for Ternary Conversion:
-
Open the Settings: Go to Settings/Preferences and navigate to Editor | Inspections.
-
Add a Custom Inspection:
- Click Add Custom Inspections.
- Select Add Structural Replace Inspection.
- In the top-right corner, set the language to Java.
-
Define the Search Template: Copy and paste the following template as the Search template:
$Type$ $var$; if ($Condition1$) $var$ = $ThenStatement$; else if ($Condition2$) $var$ = $ElseStatement1$; else $var$ = $ElseStatement2$; -
Define the Replace Template: Copy and paste the following for the Replace template:
$Type$ $var$ = $Condition1$ ? $ThenStatement$ : $Condition2$ ? $ElseStatement1$ : $ElseStatement2$; -
Save Inspection:
- Click OK to save the structural pattern.
- Click OK again in the Inspections window to apply the settings.
-
Apply the Inspection: Go to your code, place your caret at the
int x;line, press option+Enter (Mac), Alt+Enter(Windows), and IntelliJ should suggest a replacement with the ternary operator.
By following these steps, you can enable the ternary replacement for if/else chains as per your needs.
Reference
https://www.jetbrains.com/help/idea/regex-search-and-replace-inspections.html
Comments
0 comments
Please sign in to leave a comment.