Handle trailing comments in BlankLineBetweenWhenConditions (#3177)

diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBetweenWhenConditions.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBetweenWhenConditions.kt
index e763a8f..7729159 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBetweenWhenConditions.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBetweenWhenConditions.kt
@@ -99,7 +99,15 @@
         children20
             .any { it.elementType == WHEN_ENTRY && (it.textContains('\n') || it.isPrecededByComment()) }
 
-    private fun ASTNode.isPrecededByComment() = prevSibling { !it.isWhiteSpace20 }?.isPartOfComment20 ?: false
+    private fun ASTNode.isPrecededByComment(): Boolean {
+        // Check if this when-entry is preceded by a comment on its own line - not a trailing comment on the previous when-entry
+        val prevNonWhitespace = prevSibling { !it.isWhiteSpace20 }
+        if (prevNonWhitespace?.isPartOfComment20 != true) return false
+
+        // Found a comment before this when-entry, so check whether it's on its own line
+        val whitespaceBeforeComment = prevNonWhitespace.prevSibling { it.isWhiteSpace20 }
+        return whitespaceBeforeComment?.text?.contains('\n') == true
+    }
 
     private fun ASTNode.findWhitespaceAfterPreviousCodeSibling() =
         prevCodeSibling20
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBetweenWhenConditionsTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBetweenWhenConditionsTest.kt
index f85dc8e..beaca28 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBetweenWhenConditionsTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/BlankLineBetweenWhenConditionsTest.kt
@@ -24,6 +24,20 @@
     }
 
     @Test
+    fun `Given a when-statement with single line when-conditions and trailing comment then do no reformat`() {
+        val code =
+            """
+            val foo =
+                when (bar) {
+                    BAR1 -> "bar1" // Some comment
+                    BAR2 -> "bar2"
+                    else -> null
+                }
+            """.trimIndent()
+        blankLineAfterWhenConditionRuleAssertThat(code).hasNoLintViolations()
+    }
+
+    @Test
     fun `Given a when-statement with single line when-conditions only which are separated by a blank line then remove the blank lines`() {
         val code =
             """