If Else in Kotlin

Branching with if and else in Kotlin is straightforward.

fun main() {
    // Here's a basic example.
    if (7 % 2 == 0) {
        println("7 is even")
    } else {
        println("7 is odd")
    }

    // You can have an `if` statement without an else.
    if (8 % 4 == 0) {
        println("8 is divisible by 4")
    }

    // Logical operators like `&&` and `||` are often
    // useful in conditions.
    if (8 % 2 == 0 || 7 % 2 == 0) {
        println("either 8 or 7 are even")
    }

    // A statement can precede conditionals; any variables
    // declared in this statement are available in the current
    // and all subsequent branches.
    val num = 9
    if (num < 0) {
        println("$num is negative")
    } else if (num < 10) {
        println("$num has 1 digit")
    } else {
        println("$num has multiple digits")
    }
}

Note that you don’t need parentheses around conditions in Kotlin for single-line expressions, but they are required for multi-line conditions. Curly braces are always required for the body of the if-else blocks.

When you run this Kotlin program, you’ll see the following output:

7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

In Kotlin, there is a ternary-like operator using the Elvis operator (?:). For example:

val result = if (condition) trueValue else falseValue

This allows for more concise conditional assignments compared to a full if statement.