This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

Metadata

ID: kotlin-code-style/if-else-wrapping

Language: Kotlin

Severity: Notice

Category: Code Style

Description

Inconsistent formatting of our if/else statements could mislead you to their structure, especially if you have multiple nested if/else statements.

  • Use braces whenever you nest an ‘if’ statement inside another ‘if’ statement, except for if ... else if ... sequences.
  • If one of the branches of the ‘if’ statement uses braces, use braces in both branches.
  • Short, single-line branches of an ‘if’ statement should not use braces. If you must use braces, split it into several lines.

Non-Compliant Code Examples

fun foobar() {
    if (true) if (false) foo()
    if (true)
        foo()
    else
        if (false)
            bar()
    if (true) { foo() }
    if (true) {
        foo()
    } else { bar() }

    if (true) {
        foo()
    } else bar()
    if (true) foo()
    else {
        bar()
    }
}

Compliant Code Examples

fun foobar() {
    if (true) foo()
    if (true) foo() else bar()
    if (true) foo() else if (false) bar() else baz()

    if (true)
        foo()
    else if (false)
        bar()

    if (true)
        foo()
    else
        bar()

    if (true) {
        if (false) foo() else bar()
    } else {
        bar()
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Integraciones sin problemas. Prueba Datadog Code Security

PREVIEWING: guillaume.barrier/ERRORT-5095-general-doc-update