ktfmt icon indicating copy to clipboard operation
ktfmt copied to clipboard

ktfmt removes blank lines between when clauses

Open ghost opened this issue 3 years ago • 4 comments

Per https://kotlinlang.org/docs/coding-conventions.html#control-flow-statements, "In a when statement, if a branch is more than a single line, consider separating it from adjacent case blocks with a blank line"

Unfortunately, ktfmt removes such blank lines.

fun foo() {
    when {
        1 == 1 -> {
            println("The world is working okay")
        }
       
        1 > 2 -> {
            println("We may be in a parallel universe with different rules, do not proceed")
        }
    }
}

The blank line between the two cases gets removed, reproducible in https://facebookincubator.github.io/ktfmt/

ghost avatar Jul 23 '22 15:07 ghost

Sounds reasonable. Do you want to take a stab at it?

cgrushko avatar Jul 24 '22 07:07 cgrushko

Couple of questions here.

  1. The original question mentions "if a branch is more than a single line", but that's a little ambiguous. Is it referring to multi-statement blocks? Or simply blocks with braces (as in the example)? I would assume the latter.
  2. It's also not clear how to handle this. Do we insert a blank line between blocks no matter what? Or only if the user started with a blank line? For the sake of consistency, I would recommend always to insert a blank line.

salvatorebenedetto avatar Oct 27 '22 06:10 salvatorebenedetto

I guess my preference would be to preserve existing blank lines, but always inserting one also seems reasonable to me.

ghost avatar Oct 27 '22 15:10 ghost

I'd like to second this request. In code like this:

when {
    // Comment A
    condition1 -> false

    // Comment B
    condition2 ||
        condition3 ||
        condition4 -> false

    else -> true
}

...I'd like ktfmt to preserve the newline before else, so it doesn't get lumped under Comment B when it's unrelated.

Perhaps this should be a separate issue -- preserving blank lines in when clauses, versus enforcing them between two branches when either branch spans multiple lines.

juliatuttle avatar Oct 27 '23 20:10 juliatuttle

Fixed with https://github.com/facebook/ktfmt/commit/7d23e595d82342685b047ce39f1062e6d8f4a882

hick209 avatar Jun 07 '24 11:06 hick209