Ktlint: Need to wrap when statements that use an assignment if/else with a lambda

Created on 10 Sep 2020  路  2Comments  路  Source: pinterest/ktlint

Expected Behavior

I expect the following to pass formatting.

fun broken(letter: Letter): String? = when (letter) {
    Letter.A -> if (hasPrivilegedStatePermission) {
        "subscriberId"
    } else {
        throw SecurityException(
            "does not have privileged phone permission"
        )
    }
    Letter.B -> if (hasPrivilegedStatePermission) {
        "subscriberId"
    } else {
        null
    }
}

Observed Behavior

Fails with: Missing newline after "->" (indent). Wrapping with { .. } fixes the issue

Steps to Reproduce

enum class Letter(val value: String) {
    A("a"),
    B("b");
}
val hasPrivilegedStatePermission = true
fun broken(letter: Letter): String? = when (letter) {
    Letter.A -> if (hasPrivilegedStatePermission) {
        "subscriberId"
    } else {
        throw SecurityException(
            "does not have privileged phone permission"
        )
    }
    Letter.B -> if (hasPrivilegedStatePermission) {
        "subscriberId"
    } else {
        null
    }
}
fun fixed(letter: Letter): String? = when (letter) {
    Letter.A -> {
        if (hasPrivilegedStatePermission) {
            "subscriberId"
        } else {
            throw SecurityException(
                "does not have privileged phone permission"
            )
        }
    }
    Letter.B -> {
        if (hasPrivilegedStatePermission) {
            "subscriberId"
        } else {
            null
        }
    }
}

Your Environment

  • Version of ktlint used: 0.38.1 (command line)
  • AS 4.0.1 with AGP 3.6
  • Operating System and version: MacOS 10.15.6
bug

Most helpful comment

Yes, it fails on master as well.

BTW thank you for detailed bugs description :+1:

All 2 comments

This could likely be the same issue and have the same resolution as #898 (but unable to test 39.0 yet)

This is the last issue I found when upgrading to 0.38.1, so no more from me :)

Thanks!

Yes, it fails on master as well.

BTW thank you for detailed bugs description :+1:

Was this page helpful?
0 / 5 - 0 ratings