androidengineers.Book a session

Functional Programming

Lambdas & Anonymous Functions (with receiver)

article15 minMedium

A receiver changes how a lambda accesses its input

A lambda has parameters and a final result expression. An anonymous function spells out fun and can have an explicit return type. A function with receiver uses a receiver object as this inside its body.

val clean: (String) -> String = { text -> text.trim() }
val emphasize: String.() -> String = { uppercase() + "!" }
val length = fun(text: String): Int { return text.length }

fun main() {
    check(clean(" Kotlin ").emphasize() == "KOTLIN!")
    check(length("AI") == 2)
}

The receiver form is valuable in builders, but implicit this can become confusing in nested scopes. A return in an anonymous function returns from that anonymous function. Lambda returns follow lambda and inline-function rules instead, so refactoring between forms requires attention.

Exercise

Write a String.() -> Boolean predicate for nonblank text and invoke it with two receivers. Rewrite it as an ordinary one-parameter function value.

Check: both versions should express the same input and output behavior; the receiver syntax changes access, not ownership or threading.

Reference: Function literals with receiver

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Lambdas & Anonymous Functions (with receiver) | Kotlin Core Programming | Android Engineers