liveBook · Manning

Trailing lambda

As explained in Kotlin in Action, 2E

A trailing lambda is a Kotlin lambda argument written outside a function call's parentheses when it is the call's last argument.

A trailing lambda places a lambda argument outside a Kotlin function call’s parentheses when it is the final argument. This often makes calls easier to read. section 5.1.3

Equivalent call forms

These forms mean the same thing: people.maxByOrNull({ p: Person -> p.age }) people.maxByOrNull() { p: Person -> p.age } people.maxByOrNull { p: Person -> p.age } When the lambda is the only argument, omit the empty parentheses. With multiple arguments, keep the lambda outside only when it is last. A call with two or more lambdas cannot move more than one outside. section 5.1.3

Listing 5.7 Passing a lambda outside of parentheses
people.joinToString(" ") { p: Person -> p.name }

A concise collection example shows a trailing lambda used as joinToString’s final transform argument. section 5.1.3

How Kotlin in Action, 2E covers it

How deep it goes
Defines equivalent syntax, placement rules, named-argument tradeoffs, and IDE conversion, but stops short of implementation internals.
Examples
Uses maxByOrNull and joinToString calls to compare parenthesized, named, and trailing-lambda forms.
What it assumes
Assumes familiarity with Kotlin function calls and lambda expressions while demonstrating the syntax from basic forms.
What you can do after
Apply it via Kotlin syntax to write concise calls and use IDE actions to move lambda arguments.
How it connects
Connects lambda expressions with function calls, named arguments, type inference, and implicit parameter names.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.