← Back to Kotlin Course | Chapter 9: Lambdas & Higher-Order Functions | Lesson 4 of 6

The it Keyword

it is a shortcut nickname Kotlin automatically gives to a lambda's only parameter, so you don't have to name it yourself.

Using it for a Single Parameter

When a lambda takes exactly one parameter, Kotlin lets you skip naming it and refer to it simply as it inside the lambda body.

Example: Using it for a Single Parameter

markup
fun main() {
    val numbers = listOf(1, 2, 3, 4)
    val doubled = numbers.map { it * 2 }
    println(doubled)
}

Comparing it to an Explicit Name

The same lambda can be written with an explicit parameter name instead of it; both are equivalent, but explicit names are clearer for longer bodies.

Example: Comparing it to an Explicit Name

markup
fun main() {
    val numbers = listOf(1, 2, 3, 4)
    val doubledImplicit = numbers.map { it * 2 }
    val doubledExplicit = numbers.map { number -> number * 2 }
    println("Implicit: $doubledImplicit")
    println("Explicit: $doubledExplicit")
}

Avoiding Confusing Nested it

When lambdas are nested and both would use it, the inner it shadows the outer one, which can be confusing -- naming at least one of them explicitly avoids the ambiguity.

Example: Avoiding Confusing Nested it

markup
fun main() {
    val groups = listOf(listOf(1, 2), listOf(3, 4))
    val result = groups.map { group -> group.map { it * 10 } }
    println(result)
}

When to Prefer a Named Parameter

For lambdas with multi-line or complex logic, giving the parameter a descriptive name instead of it usually makes the intent much clearer to future readers.

Example: When to Prefer a Named Parameter

markup
fun main() {
    val prices = listOf(10, 25, 40)
    val withTax = prices.map { price ->
        val tax = price * 0.1
        price + tax
    }
    println(withTax)
}
Common Mistakes
  1. Using it inside a nested lambda where an outer it is also in scope, causing confusing shadowing; naming the parameter explicitly avoids this.
  2. Trying to use it in a lambda that takes more than one parameter; it only works for exactly one implicit parameter.
  3. Overusing it in long or complex lambdas where a named parameter would make the code much easier to read.
Chapter Summary
  • When a lambda has exactly one parameter and its type can be inferred, that parameter can be referred to implicitly as it.
  • it only applies to single-parameter lambdas; multi-parameter lambdas must name all their parameters explicitly.
  • Nested lambdas that both rely on implicit it can shadow each other confusingly, so naming at least the outer one is safer.
  • For longer or more complex lambda bodies, explicitly naming the parameter usually improves readability over relying on it.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.