Kotlin Lambdas and Higher-Order Functions

Kotlin course · Functions · Lesson 23 of 51

A lambda is a small function without a name that you can store in a variable or pass to another function. A higher-order function is a function that takes another function as a parameter, or returns one. Together, they’re behind most modern Kotlin code: filter, map, click listeners, Compose onClick and more.

Your first lambda

fun main() {
    val square = { x: Int -> x * x }
    println(square(4))

    val greet = { name: String -> "Hello, $name" }
    println(greet("Kotlin"))
}

Output:

16
Hello, Kotlin

A lambda is written in { }. The parameters come before ->, and the last expression is the return value. No return keyword is needed.

Function types

The type of square above is (Int) -> Int: it takes an Int and returns an Int. You can write the type explicitly:

fun main() {
    val add: (Int, Int) -> Int = { a, b -> a + b }
    val sayHi: () -> Unit = { println("Hi!") }
    val isEven: (Int) -> Boolean = { it % 2 == 0 }

    println(add(2, 3))
    sayHi()
    println(isEven(7))
}

Output:

5
Hi!
false

it: the implicit parameter

When a lambda has exactly one parameter, you can leave it out and use it:

fun main() {
    val double: (Int) -> Int = { it * 2 }
    println(double(21))

    val names = listOf("asha", "ravi", "meera")
    println(names.map { it.uppercase() })
}

Output:

42
[ASHA, RAVI, MEERA]

Higher-order functions: passing a function

fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

fun main() {
    println(calculate(10, 5) { x, y -> x + y })
    println(calculate(10, 5) { x, y -> x * y })
    println(calculate(10, 5) { x, y -> x - y })
}

Output:

15
50
5

Trailing lambda syntax

When the last parameter is a function, you can put the lambda outside the brackets, as above. If it’s the only argument, you can drop the brackets completely:

fun repeatTimes(times: Int, action: (Int) -> Unit) {
    for (i in 1..times) action(i)
}

fun runTwice(action: () -> Unit) {
    action()
    action()
}

fun main() {
    repeatTimes(3) { println("Round $it") }
    runTwice { println("Hello") }
}

Output:

Round 1
Round 2
Round 3
Hello
Hello

That’s why you see code like button.setOnClickListener { ... } and list.filter { ... }.

Lambdas with collections

fun main() {
    val prices = listOf(120, 45, 300, 80, 999)

    println(prices.filter { it > 100 })
    println(prices.map { it * 2 })
    println(prices.sortedByDescending { it })
    println(prices.any { it > 500 })
    println(prices.count { it < 100 })
}

Output:

[120, 300, 999]
[240, 90, 600, 160, 1998]
[999, 300, 120, 80, 45]
true
2

You’ll learn these collection functions in detail in the Collections module.

Returning a function

fun discount(percent: Int): (Double) -> Double {
    return { price -> price * (100 - percent) / 100 }
}

fun main() {
    val festiveSale = discount(20)
    val clearance = discount(50)
    println(festiveSale(1000.0))
    println(clearance(1000.0))
}

Output:

800.0
500.0

Function references: ::

If you already have a named function, pass it with :: instead of writing a lambda:

fun isPositive(n: Int) = n > 0

fun main() {
    val numbers = listOf(-3, 5, 0, 8, -1)
    println(numbers.filter(::isPositive))
    println(listOf("1", "2", "3").map(String::toInt).sum())
}

Output:

[5, 8]
6

Lambdas can use outside variables

A lambda can read and change variables from the code around it:

fun main() {
    var clicks = 0
    val onClick = { clicks++ }
    onClick()
    onClick()
    onClick()
    println("Clicked $clicks times")
}

Output:

Clicked 3 times

Returning from a lambda

A plain return inside a lambda returns from the outer function, which is rarely what you want. Use a label to return from the lambda only:

fun main() {
    listOf(1, 2, 3, 4).forEach {
        if (it == 3) return@forEach   // skip 3
        println(it)
    }
    println("Finished")
}

Output:

1
2
4
Finished

Common mistakes

  • Writing return in a lambda: use the last expression, or return@label.
  • Forgetting that it exists only for one parameter: with two parameters, name them: { a, b -> a + b }.
  • Overusing lambdas: if a lambda grows beyond a few lines, make it a named function and pass ::name.

Exercise

Write a function applyToAll that takes a list of numbers and a function, and returns a new list with the function applied to each number. Use it to square and negate a list.

fun applyToAll(numbers: List<Int>, transform: (Int) -> Int): List<Int> {
    val result = mutableListOf<Int>()
    for (n in numbers) result.add(transform(n))
    return result
}

fun main() {
    val nums = listOf(1, 2, 3, 4)
    println(applyToAll(nums) { it * it })
    println(applyToAll(nums) { -it })
}

Output:

[1, 4, 9, 16]
[-1, -2, -3, -4]

FAQ

What is a lambda in Kotlin?

A function without a name, written in braces, like { x: Int -> x * 2 }. You can store it in a variable or pass it to another function.

What is a higher-order function?

A function that takes a function as a parameter or returns one, for example filter, map or your own calculate(a, b) { ... }.

What does it mean in Kotlin?

The automatic name of the parameter in a lambda that has exactly one parameter.

WhatsApp us📞 Call now