Lambdas, Higher-Order Functions and Scope Functions

Article · 2:00

Passing behaviour as a value, the implicit it, and what let, apply and run are actually for.

A lambda is a function written as a value, in braces. A function that takes or returns one is a higher-order function. Every collection function in the previous topic is one, which is why they compose so freely.

Two conveniences make lambdas read well. When a lambda has exactly one parameter, you may omit the parameter list and call it it. When a lambda is the last argument to a function, it may be moved outside the parentheses - which is why apps.filter { ... } looks like built-in syntax rather than a function call. Combined, these are what make Kotlin DSLs, including Jetpack Compose, possible.

The scope functions - let, run, apply, also and with - each take a lambda and differ in two ways only: whether the object arrives as it or as this, and whether the result is the lambda's value or the object itself. Learning them as a table is far easier than learning them one at a time:

  • let - object as it, returns the lambda result. Best with ?. for null handling.
  • apply - object as this, returns the object. Best for configuring something.
  • also - object as it, returns the object. Best for a side effect such as logging.
  • run - object as this, returns the lambda result. Best for a computed block.

Resist using them everywhere. A chain of four scope functions is harder to read than three plain statements, and the compiler does not care either way.

// A higher-order function: takes behaviour as a parameter
fun <T> repeatWhile(times: Int, action: (Int) -> T): List<T> =
    (1..times).map { action(it) }

class Request {
    var url: String = ""
    var timeout: Int = 0
    override fun toString() = "$url (${timeout}ms)"
}

fun main() {
    // Trailing lambda outside the parentheses, single parameter as it
    println(repeatWhile(3) { "attempt $it" })

    // apply: object as this, returns the object - ideal for configuration
    val request = Request().apply {
        url = "https://example.com"
        timeout = 500
    }
    println(request)

    // let with a safe call: the block runs only when the value is non-null
    val name: String? = "Kotlin"
    val length = name?.let { it.length } ?: 0
    println(length)

    // also: returns the object, used for a side effect in a chain
    val doubled = listOf(1, 2, 3)
        .map { it * 2 }
        .also { println("intermediate: $it") }
        .sum()
    println(doubled)
}

Discussion

No questions on this topic yet. Sign in to ask the first one.