diff --git a/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt b/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt index 6a620222..608af596 100644 --- a/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt +++ b/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt @@ -1882,8 +1882,12 @@ class KotlinInputAstVisitor( builder.space() builder.token("{", Doc.Token.RealOrImaginary.REAL, blockIndent, Optional.of(blockIndent)) - expression.entries.forEach { whenEntry -> + expression.entries.forEachIndexed { index, whenEntry -> builder.block(blockIndent) { + if (index != 0) { + // preserve new line if there's one + builder.blankLineWanted(OpsBuilder.BlankLineWanted.PRESERVE) + } builder.forcedBreak() if (whenEntry.isElse) { builder.token("else") diff --git a/core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt b/core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt index b88138ba..4e8acc27 100644 --- a/core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt +++ b/core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt @@ -1635,6 +1635,50 @@ class FormatterTest { |""" .trimMargin()) + @Test + fun `newlines between clauses of when() are preserved`() { + assertThatFormatting( + """ + |fun f(x: Int) { + | when (x) { + | + | + | 1 -> print(1) + | 2 -> print(2) + | + | + | 3 -> + | // Comment + | print(3) + | + | else -> { + | print("else") + | } + | + | } + |} + |""" + .trimMargin()) + .isEqualTo( + """ + |fun f(x: Int) { + | when (x) { + | 1 -> print(1) + | 2 -> print(2) + | + | 3 -> + | // Comment + | print(3) + | + | else -> { + | print("else") + | } + | } + |} + |""" + .trimMargin()) + } + @Test fun `when() with a subject expression`() = assertFormatted(