liveBook · Manning

Implicit lambda parameter

As explained in Kotlin in Action, 2E

An implicit lambda parameter is the automatically generated name `it` for the sole parameter of a Kotlin lambda when its type can be inferred.

Kotlin supplies the name `it` for a lambda’s only parameter when the surrounding context can infer its type. This removes unnecessary syntax from short collection operations. section 5.5 section 5.1.3

Finding the oldest person

val people = listOf(Person("Alice", 29), Person("Bob", 31)) println(people.maxByOrNull { it.age }) // Person(name=Bob, age=31) Here, `maxByOrNull` supplies one `Person` parameter, so Kotlin infers its type and exposes that parameter as `it`. The explicit equivalent is `people.maxByOrNull { p: Person -> p.age }`. section 5.1.3

Use the shorthand selectively:

  • Prefer `it` when the lambda is short and its meaning is obvious. section 5.1.3
  • Declare the parameter explicitly when its meaning or type is unclear. section 5.1.3
  • Name parameters in nested lambdas to avoid confusing shadowing and warnings about which `it` is referenced. section 5.1.3
  • Specify parameter types when storing a lambda without an inference context. section 5.1.3
Listing 5.9 Using the default parameter name it
people.maxByOrNull { it.age }    #1

Compare the compact `it` form with the surrounding lambda-simplification steps. section 5.1.3

How Kotlin in Action, 2E covers it

How deep it goes
Explains syntax, inference conditions, explicit alternatives, stored lambdas, and nested-lambda readability limits.
Examples
Shows `people.maxByOrNull { it.age }` alongside progressively more explicit lambda forms.
What it assumes
Assumes lambda syntax and contextual type inference while demonstrating both through collection examples.
What you can do after
Apply Kotlin’s `it` shorthand and replace it with explicit parameters when clarity or inference requires.
How it connects
Connects implicit parameters with lambda expressions, type inference, collection operations, and nested lambdas.

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.