diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt index 47eefde2a6..c5a1417dcc 100644 --- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt +++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt @@ -107,10 +107,13 @@ public class MultiLineIfElseRule : // Allow single line if statements as long as they are really simple (e.g. do not contain newlines) // if (...) // no else statement // if (...) else - return + if (node.treeParent.treeParent.elementType == ELSE) { + // Except in case nested if-else-if on single line + // if (...) else if (..) + } else { + return + } } - - Unit } emit(node.firstChildNode.startOffset, "Missing { ... }", true) diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRuleTest.kt index 3f973f3474..971f3c6e29 100644 --- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRuleTest.kt +++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRuleTest.kt @@ -678,4 +678,30 @@ class MultiLineIfElseRuleTest { LintViolation(1, 53, "Missing { ... }"), ).isFormattedAs(formattedCode) } + + @Test + fun `Issue 2420 - Given a single line else-if`() { + val code = + """ + fun foo() { + if (foo) { + doFoo() + } else if (bar) doBar() + } + """.trimIndent() + val formattedCode = + """ + fun foo() { + if (foo) { + doFoo() + } else if (bar) { + doBar() + } + } + """.trimIndent() + multiLineIfElseRuleAssertThat(code) + .hasLintViolations( + LintViolation(4, 21, "Missing { ... }"), + ).isFormattedAs(formattedCode) + } }