KtKotlin · Lesson 3 of 8

Functions, when & Expressions

In Kotlin, if and when produce values. Combined with expression-body functions, half your code becomes single readable lines.

Kotlin
// Full form:
fun add(a: Int, b: Int): Int {
    return a + b
}

// Expression body — same thing:
fun add2(a: Int, b: Int) = a + b

// Default and named arguments:
fun greet(name: String, greeting: String = "Hello") =
    "$greeting, $name!"

fun main() {
    println(greet("Ada"))                       // Hello, Ada!
    println(greet("Ada", greeting = "Hey"))     // Hey, Ada!

    // if is an expression:
    val grade = 87
    val letter = if (grade >= 90) "A" else if (grade >= 80) "B" else "C"
    println(letter)
}
Kotlin
fun describe(x: Any): String = when (x) {
    0             -> "zero"
    1, 2, 3       -> "small"
    in 4..99      -> "medium"        // ranges
    is String     -> "a string of length ${x.length}"  // smart cast
    else          -> "something else"
}

fun main() {
    // Loops:
    for (i in 1..5) print(i)          // 12345 (inclusive)
    for (i in 5 downTo 1) print(i)    // 54321
    for (i in 0 until 10 step 2) print(i)  // 02468

    val fruits = listOf("apple", "banana")
    for (fruit in fruits) println(fruit)
    for ((index, fruit) in fruits.withIndex()) println("$index: $fruit")
}
✦ Tip
when replaces chains of if/else and Java's switch — no fallthrough, and when used as an expression the compiler forces you to cover every case. Reach for it whenever you branch on one value.