A lambda is a function literal: a small block of behavior written as a value. Pass one directly to a function, store it in a variable, or invoke it like a function. This avoids the boilerplate of declaring an anonymous class when all you need is behavior. section 5.1.1 section 5.1.3
Select a value from a collection
Use a lambda as the selector for a library operation: val people = listOf(Person("Alice", 29), Person("Bob", 31)) println(people.maxByOrNull { it.age }) Braces delimit the lambda. Here, it is the implicit name of the single Person parameter, and the final expression, it.age, is the value used for comparison. Kotlin infers the parameter type from maxByOrNull. If the lambda is the final argument, trailing-lambda syntax places it outside parentheses. section 5.1.2 section 5.1.3
Figure 5.1 Lambda expression syntax—a lambda is always surrounded by curly braces, specifies a number of parameters, and provides a body of the lambda which contains the actual logic.
Use the syntax diagram to identify a lambda’s braces, optional parameter list, arrow, and body before applying Kotlin’s shorthand forms. section 5.1.3
Use lambdas to make varying behavior explicit while library code handles the common structure:
- Handle events without an explicit listener object, as in button.setOnClickListener { println("I was clicked!") }. section 5.1.1
- Filter, map, aggregate, group, or transform collections with standard-library functions and predicates. section 6.1 section 6.3
- Extract a changing condition into a higher-order function rather than copy similar logic. section 10.1.6
A lambda can capture parameters and local variables from its surrounding scope. Unlike Java lambdas, Kotlin lambdas may modify captured nonfinal variables. Captured values can outlive the enclosing function when the lambda is stored for later execution, so mutable captured state deserves care. section 5.1.4
Kotlin converts a lambda passed to a Java method expecting a functional interface, such as Runnable, into an implementation of that interface. A noncapturing lambda can reuse its generated instance; a capturing lambda needs an instance that stores its captured values. Kotlin inline functions differ: passed lambdas create no anonymous classes. section 5.2.1
For control flow, a labeled return stops only the lambda and resumes after its call. Anonymous functions are an alternative function-literal form: an unlabeled return exits the nearest fun function, which is useful when several early exits would otherwise require labels. section 10.3.2 section 10.3.3

















