pinterest / ktlint

An anti-bikeshedding Kotlin linter with built-in formatter
https://pinterest.github.io/ktlint/
MIT License
6.07k stars 504 forks source link

Add rule to add braces to multiline when-condition #2557

Open paul-dingemans opened 4 months ago

paul-dingemans commented 4 months ago

Similar to the if-else-bracing rule, all branches in a when-statement should be wrapped in braces. Braces are helpful for following reasons:

Invalid:

fun foo(bar: Bar) =
    when (bar) {
        ABC_ABC_ABC_ABC -> "Lorem ipsum 1"
        DE ->
            "Lorem ipsum 2"
        FGHIJ -> {
            """
            Lorem ipsum 3
            """.trimIndent()
        }
        KLMNOPQ -> "Lorem ipsum 4"
        else -> null
    }

Valid:

fun foo(bar: Bar) =
    when (bar) {
        ABC_ABC_ABC_ABC -> {
            "Lorem ipsum 1"
        }
        DE -> {
            "Lorem ipsum 2"
        }
        FGHIJ -> {
            """
            Lorem ipsum 3
            """.trimIndent()
        }
        KLMNOPQ -> {
            "Lorem ipsum 4"
        }
        else -> {
            null
        }
    }

A when-statement for which all branches are single lines should not be affected.

Valid:

fun foo(bar: Bar) =
    when (bar) {
        ABC_ABC_ABC_ABC -> "Lorem ipsum 1"
        DE -> "Lorem ipsum 2"
        FGHIJ -> """Lorem ipsum 3""".trimIndent()
        KLMNOPQ -> "Lorem ipsum 4"
        else -> null
    }