Thuta Learning
Kotlin
AdvancedProgrammingBeginner

Lambdas

KotlinLesson 1930 min

What you'll walk away with

  • Write a lambda with explicit parameters, with it, and with a function type annotation
  • Pass a lambda as the trailing argument of a function
  • Explain what a lambda returns and why an if without else quietly changes its type
  • Predict how a closure behaves when it captures and modifies a var

Explain it simply

Lambdas in plain language

A lambda is a small function you write on the spot, without a name and without a fun declaration. It sits inside curly braces, takes its inputs before an arrow, and the value of its last line is the answer it hands back. Because Kotlin treats functions as values, you can store a lambda in a variable, pass it to another function, or return it from one.

Picture a sticky note that says 'double this number'. It has no title and nobody files it anywhere. You hand it to whoever needs the instruction, and they can follow it as many times as they like. A lambda is that sticky note, and in list.map { it * 2 } you are handing the note to map.

Problem → Why → Solution

The problem: one condition changes, the whole function gets copied

You have a list of numbers and need the even ones. You write a loop, create a result list, test every element, add the ones that pass and return the list. Next week you need numbers above 100, and the week after that, words shorter than five letters. Every new function repeats the same eight lines and changes a single condition.

The loop, the result list and the return are identical every time; only the test changes. In many languages you cannot hand 'the test' to a function, so the copy-and-paste grows with every new rule. A typo in one copy, such as < instead of <=, then hides inside a function nobody remembers writing.

copy-paste-filters.kt
fun keepEven(nums: List<Int>): List<Int> {
    val result = mutableListOf<Int>()
    for (n in nums) {
        if (n % 2 == 0) result.add(n)
    }
    return result
}

fun keepBig(nums: List<Int>): List<Int> {
    val result = mutableListOf<Int>()
    for (n in nums) {
        if (n > 100) result.add(n)
    }
    return result
}

// keepPositive, keepOdd, keepShort ... the same eight lines each time

Why passing the behaviour is the answer

A lambda lets you pass the changing part, the test, into one shared function while the loop lives in a single place. That is why Kotlin's standard library is built from functions that take lambdas: filter owns the loop and you supply only the condition. Fewer copies means fewer places for the same mistake, and the call site reads like a description of what you want, as in numbers.filter { it > 100 }.

Core concept: lambdas, function types and closures

A lambda expression has three parts: curly braces, an optional parameter list and a body. The shape is { a: Int, b: Int -> a + b }. The parameters come first, the arrow separates them from the body, and the body holds one or more statements. There is no return keyword: the value of the last expression becomes the value of the lambda, so x + y on its own is enough. Kotlin gives { x: Int, y: Int -> x + y } the function type (Int, Int) -> Int, which reads 'takes two Ints, returns an Int'.

Function types are ordinary types. You can write one for a variable (val op: (Int, Int) -> Int), a parameter (action: (String) -> Unit) or a return type (fun makeCounter(): () -> Int). When the expected type is already known, Kotlin infers the parameter types, so val double: (Int) -> Int = { n -> n * 2 } needs no annotation inside the braces. You call a function value like any function, double(21), which behind the scenes is double.invoke(21).

Two shortcuts keep lambdas short. First, a lambda with exactly one parameter can leave it unnamed and use the implicit name it, so { n -> n * 2 } becomes { it * 2 }. Use it for short bodies and give the parameter a real name once the body grows or lambdas are nested, because two nested its are hard to read. Second, if the last parameter of a function is itself a function, the lambda may be written after the closing parenthesis, and if it is the only parameter the parentheses disappear. numbers.filter({ it > 2 }) and numbers.filter { it > 2 } are the same call, and the second is the style you will read everywhere.

FormExampleFunction type
Explicit parameters{ x: Int, y: Int -> x + y }(Int, Int) -> Int
Implicit itval f: (Int) -> Int = { it * 3 }(Int) -> Int
No parameters{ println("ping") }() -> Unit
Trailing lambdarepeat(2) { println(it) }(Int) -> Unit parameter

The most surprising ability is the closure. A lambda can read and modify the variables of the function that created it, vars included, and it keeps them alive for as long as the lambda exists. Kotlin does not copy the value; the lambda shares the variable itself. That is why a counter built from a lambda keeps counting after the function that created it has returned (see the deeper section below). Java lambdas can only capture effectively final variables, so this is a real difference for people arriving from Java.

A lambda is a function you can carry
  1. Braces create a function value
  2. Parameters come before the arrow
  3. The last expression is returned
  4. Captured variables are shared, not copied

If a lambda returns the wrong thing, check its last line first: whatever that line evaluates to is the result.

General pattern

kotlin
val name: (ParamType) -> ReturnType = { param -> lastExpression }

val name = { param: ParamType -> lastExpression }

val name: (ParamType) -> ReturnType = { it ... }

fun use(action: (ParamType) -> ReturnType) { ... }

use { param -> lastExpression }

Choose the form by who supplies the types: write the function type on the variable and keep the braces short, or type the parameters inside the braces and let Kotlin infer the function type. A function that takes a function as its last parameter can be called with the lambda outside the parentheses.

Worked example: a lambda stored in a variable

The program below stores a lambda in sum and calls it like an ordinary function. The only name in play is the variable sum: the lambda itself is anonymous, and its type is inferred from the parameter annotations. Work out the output in your head before you run it.

kotlin
fun main() {
    val sum = { x: Int, y: Int -> x + y }
    println("Sum of 5 and 3 is ${sum(5, 3)}")
}

Code breakdown

  1. Function literalval sum = { x: Int, y: Int -> x + y }

    The braces create a function value and the arrow separates parameters from body. Both parameters are typed because nothing else tells Kotlin what x and y are, and from those annotations Kotlin infers the type (Int, Int) -> Int for sum. The lambda has no name of its own; sum is just the variable holding it.

  2. Implicit returnx + y

    There is no return keyword. The last expression, here the only one, x + y, is the value the lambda hands back, so a call to sum(5, 3) evaluates to 8.

  3. Calling a function valuesum(5, 3)

    A variable of function type is called with parentheses, exactly like a function declared with fun. Kotlin rewrites sum(5, 3) into sum.invoke(5, 3) behind the scenes.

  4. Call inside a templateprintln("Sum of 5 and 3 is ${sum(5, 3)}")

    The call sits inside a string template, so the lambda runs while the string is being built and its result, 8, is inserted. The final output is the single line Sum of 5 and 3 is 8.

You should see
Sum of 5 and 3 is 8

Closures: a lambda remembers its surroundings

Every call to makeCounter creates a fresh count variable of its own and returns a lambda that modifies it. Normally count would vanish when makeCounter finishes, but the lambda captured it, so it lives as long as the lambda does. Two counters each own a separate variable, so one never disturbs the other.

closure-counter.kt
fun makeCounter(): () -> Int {
    var count = 0
    return {
        count += 1
        count
    }
}

fun main() {
    val first = makeCounter()
    val second = makeCounter()
    println(first())
    println(first())
    println(first())
    println(second())

    var clicks = 0
    val onClick = { clicks++ }
    onClick()
    onClick()
    println("clicks = $clicks")
}
text
Each makeCounter() call owns its own captured variable
------------------------------------------------------
first = makeCounter()            second = makeCounter()
   |                                |
   +--> lambda --> count (a box)    +--> lambda --> count (a box)
                   value: 3                         value: 1

Output: 1, 2, 3 from first, then 1 from second.

The program prints 1, 2, 3, 1 and then clicks = 2. The clicks++ inside onClick increments the very clicks variable declared in main, so after two calls the outer clicks holds 2. A closure therefore holds a shared variable, not a private copy.

What a lambda returns: labels, Unit and else

A lambda has no function of its own to return from, so return follows special rules. To give back a result, make it the last expression; to skip one element, return with a label such as return@forEach. In the sample below the lambda passed to map ends with an if/else expression, so it yields label strings. The map that ends with a println yields a list full of Unit values instead.

lambda-results.kt
fun main() {
    val numbers = listOf(3, 8, 1, 9)
    val labels = numbers.map { n ->
        if (n > 5) "big" else "small"
    }
    println(labels)

    numbers.forEach {
        if (it == 1) return@forEach
        println("saw $it")
    }

    val noValue = numbers.map { println("visit $it") }
    println(noValue)
}

A forgotten else changes the type

val label = { score: Int -> if (score >= 50) "pass" } compiles, but because the if is not used as an expression the lambda has type (Int) -> Unit, and label(70) prints kotlin.Unit. Only when the variable is declared as (Int) -> String does the compiler complain: initializer type mismatch: expected 'Function1<Int, String>', actual 'Function1<Int, Unit>'. Adding else "fail" fixes it.

In real projects

Where lambdas show up in real projects

Lambdas are the glue of everyday Kotlin. An Android screen registers behaviour with button.setOnClickListener { ... }, a Ktor server describes routes with get("/health") { ... }, and Gradle's Kotlin DSL configures a build with blocks such as dependencies { ... }. In each case the framework owns the plumbing and you hand it a small piece of behaviour. Much of the standard library works the same way: sortedBy, filter, lazy, buildString and thread all take a lambda.

A habit worth building early is keeping lambdas short. When one grows past five or six lines, give it a name with fun and pass ::name instead, so the call site stays readable and the logic can be tested on its own.

  • UI callbacks: click, text-changed and refresh handlers are lambdas that the framework calls later.
  • Collection pipelines: filter, map and sortedBy take the condition or the key as a lambda.
  • Deferred work: lazy { ... } runs its lambda on first access, and runCatching { ... } runs it inside a safety net.

Common mistakes

Common mistakes with lambdas

Ending a lambda with a statement that is not the value you wanted

A lambda returns the value of its last line. Add a println to the end of a map body while debugging and numbers.map { println(it) } quietly becomes a List<Unit>. An if without else follows the same path: it compiles, but the type turns into (Int) -> Unit. If you intend to use the result, check that the last line produces a value and that every if has its else.

Using return as if the lambda were a function

In a lambda passed to a non-inline function, a bare return is rejected with 'return' is prohibited here. Inside an inline function such as map or forEach it is allowed but returns from the enclosing function, so the rest of the loop never runs. To skip one element write return@forEach; to produce a value, make it the last expression.

Assuming a closure copies the variable

A lambda that captures clicks shares that variable with the code that created it. If the outer code changes it later the lambda sees the new value, and if the lambda changes it the outer code sees that too. When you want a snapshot in time, copy the value into a new val before creating the lambda and use that val inside it.

Best practices

Best practices

  • Name the parameter when a lambda is longer than a line or when lambdas are nested; keep it for short bodies.
  • Write the function type on the variable or parameter so readers see the contract: (Order) -> Boolean says more than a comment.
  • Prefer a trailing lambda for the last parameter, and pull anything longer than a few lines out into a named function.
  • Keep captured vars to a minimum: a lambda that mutates outside state is harder to test than one that returns a value.

Mini challenge

Mini challenge: multipliers, counters and a table of operations

Build three small pieces with lambdas. makeMultiplier(factor) returns a function that multiplies its argument by factor. makeCounter() returns a function that gives 1, 2, 3 ... on successive calls, and two counters must not share their count. Finally, store the operations add, sub and mul in a map and apply each one to the same pair of numbers.

  • makeMultiplier returns a value of type (Int) -> Int and is used to build double and triple
  • makeCounter keeps its count in a captured var, and two counters count independently
  • A Map<String, (Int, Int) -> Int> holds add, sub and mul, and a loop prints name(12, 4) = result
  • Print double(7), triple(7), one counter called three times and a second counter called once
lambda-challenge.kt
// TODO: return a lambda that multiplies its argument by factor
fun makeMultiplier(factor: Int): (Int) -> Int {
    TODO()
}

// TODO: declare a var inside, and return a lambda that increases it and gives it back
fun makeCounter(): () -> Int {
    TODO()
}

fun main() {
    // TODO: a Map<String, (Int, Int) -> Int> with "add", "sub" and "mul"
    // TODO: loop over it and print name(12, 4) = result

    // TODO: build double and triple with makeMultiplier, print double(7) and triple(7)

    // TODO: two counters: call one three times, the other once, print all four numbers
}

Expected: The map loop prints add(12, 4) = 16, sub(12, 4) = 8 and mul(12, 4) = 48. Then double(7) = 14, triple(7) = 21, and the counters print 1 2 3 1.

Show hint

A lambda can be a function's body: fun makeMultiplier(factor: Int): (Int) -> Int = { value -> ... }. For the counter, declare var count = 0 inside makeCounter, before the lambda, and change it inside the lambda.

Show solution
lambda-challenge.kt
fun makeMultiplier(factor: Int): (Int) -> Int = { value -> value * factor }

fun makeCounter(): () -> Int {
    var count = 0
    return { ++count }
}

fun main() {
    val operations: Map<String, (Int, Int) -> Int> = mapOf(
        "add" to { a, b -> a + b },
        "sub" to { a, b -> a - b },
        "mul" to { a, b -> a * b },
    )
    for ((name, op) in operations) {
        println("$name(12, 4) = ${op(12, 4)}")
    }

    val double = makeMultiplier(2)
    val triple = makeMultiplier(3)
    println("double(7) = ${double(7)}, triple(7) = ${triple(7)}")

    val a = makeCounter()
    val b = makeCounter()
    println("${a()} ${a()} ${a()} ${b()}")
}

Quick quiz 1 / 3

makeCounter() declares var count = 0 and returns { count += 1; count }. After val a = makeCounter(), val b = makeCounter(), a() and a(), what does println(b()) print?

Quick quiz 2 / 3

What is the type of val f = { a: Int, b: Int -> a + b }?

Quick quiz 3 / 3

println(listOf(1, 2, 3).map { println(it) }) prints 1, 2 and 3. What does its final line show?

What to remember

  • A lambda is a function value shaped { parameters -> body }, and its last expression is the returned value.
  • A function type such as (Int, Int) -> Int works for variables, parameters and return types, and a lone parameter can simply be called it.
  • When a function's last parameter is a function, use a trailing lambda written outside the parentheses.
  • A closure shares the captured variable itself, vars included, and an if without else can make a lambda return Unit.

Kotlin language guide — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Lambdas | Thuta Learning