if as an Expression

if Returns a Value

In Kotlin if is an expression: it produces a value. That is why Kotlin has no ternary operator a ? b : c like Java.

Example

Assign the result of if directly to a variable.

fun main() {
    val age = 16
    val ticket = if (age < 18) "Child" else "Adult"
    println(ticket)

    val a = 42
    val b = 17
    val max = if (a > b) a else b
    println("Max: $max")
}

Output

Child
Max: 42

Blocks as Values

Example

When a branch is a block, the last expression in the block is its value. As an expression, if must have an else.

fun main() {
    val orderTotal = 650
    val deliveryFee = if (orderTotal >= 500) {
        println("Free delivery unlocked!")
        0
    } else {
        println("Add ₹${500 - orderTotal} more for free delivery")
        40
    }
    println("Delivery fee: ₹$deliveryFee")
}

Output

Free delivery unlocked!
Delivery fee: ₹0
// Java ternary
String ticket = age < 18 ? "Child" : "Adult";
// Kotlin
val ticket = if (age < 18) "Child" else "Adult"