SDSnipDojo
← All lessons
Lesson 11 / 126 steps3 exercises

Lambdas

Anonymous functions, higher-order functions, and trailing lambdas.

1. Lambdas

A lambda is an anonymous function — a chunk of code you can pass around like a value. Curly braces wrap it; -> separates parameters from the body:

val twice: (Int) -> Int = { it * 2 }
twice(5)                    // 10

For a single argument, it is its implicit name. With multiple arguments, name them explicitly:

val add: (Int, Int) -> Int = { a, b -> a + b }
add(2, 3)                   // 5

2. apply2

Implement apply2(n, fn) calling fn(n) and returning the result. The harness will pass different lambdas like { it * 2 }.

Starter code

fun apply2(n: Int, fn: (Int) -> Int): Int {
    return n
}

3. Higher-order functions

A function that takes another function as a parameter is called higher-order. map and filter are the most famous examples — they take a lambda and apply it.

You can write your own:

fun applyAll(list: List<Int>, fn: (Int) -> Int): List<Int> = list.map(fn)

applyAll(listOf(1, 2, 3)) { it * 2 }     // [2, 4, 6]

Note the parameter type (Int) -> Int — that's a function from Int to Int.

4. applyAll

Implement applyAll(list, fn) returning a new list with fn applied to every element. Hint: list.map(fn) does exactly this.

Starter code

fun applyAll(list: List<Int>, fn: (Int) -> Int): List<Int> {
    return list
}

5. Trailing lambdas

When a lambda is the last argument, you can write it outside the parentheses. These two are identical:

apply2(5, { it * 2 })
apply2(5) { it * 2 }      // trailing lambda — much cleaner

That's why Kotlin code reads so well — listOf(1, 2, 3).map { it * 2 } is just map with a trailing lambda. When the lambda is the only argument, you can drop the parens entirely:

listOf(1, 2, 3).map { it * 2 }

6. times — trailing lambda

Implement times(n, action) that invokes action() exactly n times. The harness uses trailing-lambda syntax: times(5) { count++ }.

Starter code

fun times(n: Int, action: () -> Unit) {
    // call action n times
}

Run this Kotlin lesson in your browser

SnipDojo ships an in-browser Kotlin editor with the exercises above already wired to tests. Sign in with Google to edit the starter code, run it, and track your progress toward the free certificate — no installs and no local toolchain.

Sign in to run this code →