Kotlin · Module 3 · Lesson 21 min read

Lambdas & Higher-Order Functions

Lambdas

kotlin
val square = { x: Int -> x * x }
val add: (Int, Int) -> Int = { a, b -> a + b }
square(4)          // 16
  • Written in { params -> body }; the last expression is the result.
  • A function type looks like (Int, Int) -> Int.
  • With one parameter, you can use it: { it * 2 }.

Higher-order functions

A function that takes or returns a function:

kotlin
fun calculate(a: Int, b: Int, op: (Int, Int) -> Int) = op(a, b)
calculate(6, 3) { x, y -> x * y }      // 18

Trailing lambda syntax

If the last parameter is a function, the lambda goes outside the brackets, and if it's the only argument, the brackets disappear:

kotlin
list.filter { it > 3 }
button.setOnClickListener { showToast() }
repeat(3) { println(it) }

This is why Kotlin code (and Jetpack Compose) reads so cleanly.

Function references

list.map(::double) passes an existing function; String::length refers to a member.

Returning functions

kotlin
fun multiplier(k: Int): (Int) -> Int = { it * k }
val triple = multiplier(3)

Lambdas can capture variables from their surroundings (closures).

inline functions

Higher-order functions marked inline (like filter and map) copy the lambda body to where it's called, so there's no performance cost.

Example

kotlin
fun calculate(a: Int, b: Int, op: (Int, Int) -> Int): Int = op(a, b)

fun multiplier(k: Int): (Int) -> Int = { it * k }

fun double(x: Int) = x * 2

fun main() {
    val square = { x: Int -> x * x }
    val add: (Int, Int) -> Int = { a, b -> a + b }
    println(square(4))                          // 16
    println(add(2, 3))                          // 5

    println(calculate(6, 3) { x, y -> x * y })  // 18 — trailing lambda
    println(calculate(6, 3, add))               // 9

    val triple = multiplier(3)
    println(triple(7))                          // 21

    val nums = listOf(1, 2, 3, 4, 5, 6)
    println(nums.filter { it % 2 == 0 })        // [2, 4, 6]
    println(nums.map(::double))                 // function reference
    println(listOf("kotlin", "is", "fun").map(String::length))   // [6, 2, 3]

    var clicks = 0
    val onClick = { clicks++; println("Clicked $clicks time(s)") }   // captures clicks
    repeat(3) { onClick() }
}