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
Compare the compact `it` form with the surrounding lambda-simplification steps. section 5.1.3
