Skip to content
LumenaryAcademy
Foundations 60 min

Control flow, when and functions

Expressions instead of statements, the when expression, ranges and loops, and Kotlin's functions, from default and named arguments to extension functions and lambdas.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

Everything that can be a value, is

In Java, if is a statement: it does something, and if you want a value you need the separate conditional operator. switch was a statement for twenty years before it gained an expression form. In Kotlin, almost every construct that makes a choice is an expression that produces a value: if, when, try, even a block of code passed as a lambda. The result is code with fewer temporary variables and fewer "assign in each branch" patterns, where a reader sees at a glance that a variable gets exactly one value.

Functions get the same treatment. A Kotlin function can live at the top level of a file, inside another function, or "on" an existing type as an extension. It can be passed to another function, returned from one, or stored in a map. Default and named arguments remove most of the overloads that Java needs, and lambdas with their trailing syntax make code that takes functions read like built-in language constructs. Much of what makes Kotlin feel concise comes from these few ideas, so this lesson covers them carefully.

DefinitionsH

Definitions

Definition— when

Kotlin's multi-way choice. With a subject, when (x) { ... }, each branch tests the subject: against values ("Saturday", "Sunday" ->), ranges (in 1..9 ->) or types (is String ->). Without a subject, each branch is an arbitrary boolean condition. Used as an expression, when must be exhaustive, usually by ending with else. Since Kotlin 2.2 a branch may add a guard, is Int if x < 0 ->.

Definition— Range and progression

a..b is the closed range from a to b; a..<b excludes b; b downTo a counts down; step n skips. They work for integers and characters, and in tests membership.

Definition— Extension function

A function declared as fun String.initials(): String, callable as if it were a method of String ("ada lovelace".initials()). Inside it, this is the receiver. The class itself is not modified; the extension is a static function that takes the receiver as its first argument, chosen at compile time by the receiver's declared type.

Definition— Function type and lambda

(Int) -> Int is the type of functions from Int to Int; () -> Unit takes nothing and returns nothing. A lambda { x -> x * 2 } is a function value; if it has one parameter, it may be called it. A function reference ::isPrime turns a named function into a value.

Definition— Closure

A lambda that captures variables from the scope where it was created, and keeps them alive. In Kotlin, captured vars can be modified by the lambda.

Worked examplesH

when, ranges and loops

kotlin
fun describeTemperature(celsius: Int): String = when {
    celsius < 0 -> "freezing"
    celsius < 15 -> "cold"
    celsius < 25 -> "mild"
    else -> "hot"
}

fun dayType(day: String): String = when (day) {
    "Saturday", "Sunday" -> "weekend"
    "Friday" -> "almost weekend"
    else -> "weekday"
}

fun describe(x: Any): String = when (x) {
    0 -> "zero"
    in 1..9 -> "a single digit"
    is Int if x < 0 -> "a negative Int"            // guard condition (Kotlin 2.2)
    is Int -> "a larger Int"
    is String -> "text of length ${x.length}"
    else -> "something else"
}

fun main() {
    println(listOf(-5, 8, 21, 33).joinToString(" ") { describeTemperature(it) })
    println(dayType("Friday") + ", " + dayType("Sunday") + ", " + dayType("Tuesday"))
    println(listOf(0, 7, -4, 250, "hi", 2.5).map { describe(it) })

    // Ranges and progressions
    println((1..10 step 3).toList())
    println((10 downTo 0 step 5).toList())
    println((0..<5).toList())
    println(7 in 1..10)

    // while and do-while
    var n = 27
    var steps = 0
    while (n != 1) {
        n = if (n % 2 == 0) n / 2 else 3 * n + 1
        steps++
    }
    println("27 reaches 1 after $steps steps")

    // Labels: break out of the outer loop from the inner one
    var found = ""
    outer@ for (i in 1..9) {
        for (j in 1..9) {
            if (i * j == 42) {
                found = "$i x $j"
                break@outer
            }
        }
    }
    println("first pair with product 42: $found")

    repeat(3) { index -> print("tick$index;") }
    println()
}
text
freezing cold mild hot
almost weekend, weekend, weekday
[zero, a single digit, a negative Int, a larger Int, text of length 2, something else]
[1, 4, 7, 10]
[10, 5, 0]
[0, 1, 2, 3, 4]
true
27 reaches 1 after 111 steps
first pair with product 42: 6 x 7
tick0;tick1;tick2;

The three when functions show its three styles:

  • Without a subject (describeTemperature), each branch is a condition, checked top to bottom; the first true one wins. This replaces if/else if chains and is easier to scan.
  • With a subject and constants (dayType), several values can share a branch, separated by commas. There is no fall-through, ever.
  • With a subject of type Any (describe), branches can mix constants, range tests and type tests. After is String ->, the subject is smart-cast, so x.length works. The guard is Int if x < 0 adds a condition to a type test; it arrived as a stable feature in Kotlin 2.2.

All three are used as expressions, so each needs an else (the compiler cannot otherwise be sure every input produces a value). When the subject is an enum, a Boolean or a sealed type, a when that lists every case needs no else, and the compiler will complain when a new case is added. That is the most valuable use of when, and it comes back in the next lesson.

Loops are simple: for iterates over anything with an iterator (ranges, collections, strings, maps); while and do/while work as in Java. There is no C-style for (i = 0; i < n; i++): you write for (i in 0..<n), or better, for (item in list), or for ((index, item) in list.withIndex()). A label (outer@) lets break and continue target an outer loop. repeat(n) { ... } is a standard-library function that runs a lambda n times.

Worked examplesH

Functions: defaults, names, extensions

kotlin
// Default and named arguments replace most overloads
fun formatPrice(amount: Double, currency: String = "KES", decimals: Int = 2, symbolFirst: Boolean = false): String {
    val number = "%.${decimals}f".format(java.util.Locale.ROOT, amount)
    return if (symbolFirst) "$currency $number" else "$number $currency"
}

// A single-expression function
fun average(vararg values: Int): Double = if (values.isEmpty()) 0.0 else values.sum().toDouble() / values.size

// Extension functions add methods to existing types, without changing them
fun String.initials(): String = split(" ").filter { it.isNotBlank() }.joinToString("") { it.first().uppercase() }
val Int.isEven: Boolean get() = this % 2 == 0          // an extension property

// An infix function reads like an operator
infix fun Int.percentOf(total: Int): Double = 100.0 * this / total

// tailrec: the compiler turns this recursion into a loop
tailrec fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)

fun main() {
    println(formatPrice(1250.5))
    println(formatPrice(1250.5, "USD", symbolFirst = true))
    println(formatPrice(amount = 99.0, decimals = 0, currency = "JPY"))

    println(average(4, 8, 15, 16, 23, 42))
    val scores = intArrayOf(70, 80, 90)
    println(average(*scores))                          // spread an array into varargs

    println("ada lovelace".initials() + " " + "grace  brewster hopper".initials())
    println("${10.isEven} ${7.isEven}")
    println(45 percentOf 60)
    println(gcd(1_071, 462))

    // A local function, visible only inside main
    fun shout(s: String) = s.uppercase() + "!"
    println(shout("done"))
}
text
1250.50 KES
USD 1250.50
99 JPY
18.0
80.0
AL GBH
true false
75.0
21
DONE!

Default and named arguments. formatPrice has one required parameter and three with defaults. Callers pass only what differs from the default, and can name arguments to skip some or to make a call self-explanatory: formatPrice(1250.5, "USD", symbolFirst = true) says more than formatPrice(1250.5, "USD", 2, true). Named arguments can come in any order. In Java the same API would need several overloads or a builder. (Formatting uses Locale.ROOT so the decimal separator is a point on every machine; with the default locale, a German system would print a comma.)

Single-expression functions replace braces and return with =, and the return type can usually be inferred, though public functions in libraries should state it. vararg parameters arrive as an array; the spread operator * passes an existing array where a vararg is expected.

Extensions. "ada lovelace".initials() reads as if String had a method called initials. It does not: the compiler turns the call into initials("ada lovelace"), a static function call. Extensions are how Kotlin's standard library adds hundreds of convenient functions (split, filter, joinToString, uppercase) to Java's existing classes without wrappers, and how you can give a library type the vocabulary of your domain. An extension property like isEven works the same way but cannot store state; it has only a getter.

Infix functions (one parameter, marked infix) can be called without a dot or parentheses: 45 percentOf 60. The standard library's to, as in "+" to 1, is an infix function that builds a pair. Use infix sparingly, for things that genuinely read like operators.

tailrec asks the compiler to turn a function whose recursive call is the very last thing it does into a loop, so it cannot overflow the stack. If the call is not in tail position, the compiler warns that it cannot apply the optimisation.

ComputationC

Lambdas, closures and inline functions

kotlin
// A higher-order function: it takes a function as a parameter
fun applyTwice(x: Int, f: (Int) -> Int): Int = f(f(x))

// ...and one that returns a function
fun multiplier(factor: Int): (Int) -> Int = { x -> x * factor }

// A function that remembers state between calls (a closure)
fun counter(): () -> Int {
    var count = 0
    return { ++count }
}

fun isPrime(n: Int): Boolean = n > 1 && (2..<n).none { n % it == 0 }

fun firstNegative(numbers: List<Int>): Int? {
    numbers.forEach {
        if (it < 0) return it          // forEach is inline, so this returns from firstNegative
    }
    return null
}

fun main() {
    println(applyTwice(3) { it * 10 })                 // trailing lambda syntax
    val triple = multiplier(3)
    println(triple(14))

    val next = counter()
    next(); next()
    println(next())

    val numbers = listOf(12, 7, 5, 20, 11, -3, 4)
    println(numbers.filter(::isPrime))                  // a function reference
    println(numbers.map { n -> n * n }.take(3))
    println(numbers.sortedBy { -it })
    println(firstNegative(numbers))

    // return@label returns from the lambda only
    val kept = mutableListOf<Int>()
    numbers.forEach {
        if (it % 2 == 0) return@forEach                // skip even numbers, keep looping
        kept += it
    }
    println(kept)

    // Function types can be stored in variables and collections
    val operations: Map<String, (Double, Double) -> Double> = mapOf(
        "+" to { a, b -> a + b },
        "*" to { a, b -> a * b },
        "max" to ::maxOf,
    )
    for ((name, op) in operations) println("$name: ${op(6.0, 7.0)}")
}
text
300
42
3
[7, 5, 11]
[144, 49, 25]
[20, 12, 11, 7, 5, 4, -3]
-3
[7, 5, 11, -3]
+: 13.0
*: 42.0
max: 7.0

Trailing lambdas. When a function's last parameter is a function, the lambda can go outside the parentheses: applyTwice(3) { it * 10 }. If it is the only argument, the parentheses disappear entirely: numbers.map { n -> n * n }. This is why Kotlin libraries and DSLs (Gradle build files, HTML builders, test frameworks) look like they have their own syntax: they are just functions taking lambdas.

Functions as values. multiplier(3) returns a function, which is stored in triple and called like any function. ::isPrime turns a named function into a value that filter can call. The operations map stores three functions under string keys; ::maxOf refers to the standard library's maxOf.

Closures. Each call to counter() creates a new count variable and a lambda that captures it. The lambda outlives the call that created it, and every call to next() updates the same captured count. Unlike Java, which only lets lambdas capture effectively final variables, Kotlin allows capturing and modifying a var (the compiler wraps it in a small object behind the scenes).

inline and returns. Most collection functions that take lambdas (forEach, map, filter, let...) are declared inline: the compiler copies the function body and the lambda into the call site, so no function object is created at all. A side effect is that a plain return inside such a lambda returns from the enclosing function, a non-local return, which is what firstNegative relies on. To leave only the lambda, use a labelled return such as return@forEach, which here acts like continue. In a non-inline lambda a bare return is not allowed, so you cannot get this wrong silently.

Since Kotlin 2.2, break and continue may also appear inside an inline lambda such as forEach when it sits inside a loop; like a non-local return, they act on that enclosing loop.

Worked examplesH

From Java-style to idiomatic Kotlin

Example— Rewriting a shipping-cost function

Here is a function as someone fresh from Java might first write it in Kotlin. It compiles and works:

kotlin
fun shippingCost(weightKg: Double, express: Boolean, country: String): Double {
    var cost: Double
    if (country == "KE" || country == "UG" || country == "TZ") {
        cost = 300.0
    } else if (country == "RW") {
        cost = 450.0
    } else {
        cost = 1200.0
    }
    cost = cost + weightKg * 50
    if (express) {
        cost = cost * 1.5
    }
    return cost
}

Three things make it un-idiomatic: a var assigned in every branch, an if/else if chain testing one value, and a boolean parameter that will be unreadable at call sites (shippingCost(2.0, true, "RW"): true what?). Rewritten:

kotlin
fun shippingCost(weightKg: Double, country: String, express: Boolean = false): Double {
    val base = when (country) {
        "KE", "UG", "TZ" -> 300.0
        "RW" -> 450.0
        else -> 1200.0
    }
    val cost = base + weightKg * 50
    return if (express) cost * 1.5 else cost
}

// at the call site
shippingCost(2.0, "RW", express = true)

Every name now has exactly one value, the country table reads like a table, and the call says what true means. The default value for express also lets the common case omit it. Nothing here is clever; it is the same logic with the language doing more of the bookkeeping. When reviewing Kotlin code, "could this var be a val assigned from an expression?" is one of the most useful questions to ask.

ExplanationH

How experienced Kotlin developers use these

  • Prefer expressions. val label = when (...) { ... } over a var assigned in each branch. If a function's body is a single expression, write it with =.
  • Default arguments over overloads, named arguments for clarity. Name any boolean or numeric argument whose meaning is not obvious at the call site, and every argument when there are several of the same type.
  • Extensions for vocabulary, not for hiding logic. A handful of extensions that make domain code read well (order.totalWithTax()) are good. Extensions that reach into unrelated types, or that surprise readers by shadowing member functions, are not. Members always win over extensions with the same signature.
  • Small lambdas inline, big ones named. A lambda longer than a few lines is usually clearer as a named function passed by reference.
  • Know what it means. In nested lambdas, two its are confusing; name the parameters.
Common misconceptionsH

Common misconceptions

Misconception

"Extension functions are virtual, like methods." They are resolved statically from the declared type. If Shape.name() and Circle.name() are both extensions and a variable is declared as Shape, calling name() on it uses the Shape version, even if the object is a Circle. Use member functions (and open/override) when you need dynamic dispatch.

Misconception

"return inside a lambda returns from the lambda." In an inline lambda (such as forEach), a bare return leaves the enclosing function. Use return@forEach to leave just the lambda.

Misconception

"A when expression is just a nicer switch with fall-through." There is no fall-through at all, and branches can test ranges, types and arbitrary conditions.

Misconception

"Default arguments work the same way when Java calls my function." Java has no default arguments, so it sees only the full signature. Annotate the function with @JvmOverloads if Java callers need the shorter forms.

Exercises

Exercises

1. Control flow, when and functions

Warm-upComputational

What does this program print?

fun size(n: Int) = when {
    n < 10 -> "S"
    n < 100 -> "M"
    else -> "L"
}

fun main() {
    println(listOf(5, 50, 500, 10).joinToString("") { size(it) })
}

2. Control flow, when and functions

CoreComputational

What does this program print?

fun box(text: String, left: String = "[", right: String = "]") = left + text + right

fun main() {
    println(box("a") + box("b", right = ">") + box(right = "|", text = "c", left = "|"))
}

3. Control flow, when and functions

CoreComputational

What does this program print?

fun counter(): () -> Int {
    var c = 0
    return { c += 2; c }
}

fun main() {
    val a = counter()
    val b = counter()
    a(); a(); b()
    println(a() * 10 + b())
}

4. Control flow, when and functions

Warm-upComputational

What does this program print?

fun main() {
    println((1..10 step 4).toList())
}

5. Control flow, when and functions

StretchComputational

What does this program print?

fun sumUntilZero(xs: List<Int>): Int {
    var s = 0
    xs.forEach {
        if (it == 0) return s
        s += it
    }
    return -1
}

fun main() {
    println(sumUntilZero(listOf(3, 4, 0, 5)))
}

6. Control flow, when and functions

StretchComputational

What does this program print?

open class Shape
class Circle : Shape()

fun Shape.name() = "shape"
fun Circle.name() = "circle"

fun main() {
    val s: Shape = Circle()
    println(s.name())
}

7. Control flow, when and functions

CoreHuman

fun label(n: Int): String = when { n > 0 -> "positive"; n < 0 -> "negative" } does not compile. Why?

Choose one

Further reading and resources