Kotlin Conditional Statements When-statement instead of if-else-if chains


Example

The when-statement is an alternative to an if-statement with multiple else-if-branches:

when {
    str.length == 0 -> print("The string is empty!")
    str.length > 5  -> print("The string is short!")
    else            -> print("The string is long!")
}

Same code written using an if-else-if chain:

if (str.length == 0) {
    print("The string is empty!")
} else if (str.length > 5) {
    print("The string is short!")
} else {
    print("The string is long!")
}

Just like with the if-statement, the else-branch is optional, and you can add as many or as few branches as you like. You can also have multiline-branches:

when {
    condition -> {
        doSomething()
        doSomeMore()
    }
    else -> doSomethingElse()
}