The it Keyword
In this page:
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
fun main() {
val numbers = listOf(1, 2, 3, 4)
val doubled = numbers.map { it * 2 }
println(doubled)
}
Login to try C/C++/Java/PHP code in the editor
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
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")
}
Login to try C/C++/Java/PHP code in the editor
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
fun main() {
val groups = listOf(listOf(1, 2), listOf(3, 4))
val result = groups.map { group -> group.map { it * 10 } }
println(result)
}
Login to try C/C++/Java/PHP code in the editor
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
fun main() {
val prices = listOf(10, 25, 40)
val withTax = prices.map { price ->
val tax = price * 0.1
price + tax
}
println(withTax)
}
Login to try C/C++/Java/PHP code in the editor
- Using
itinside a nested lambda where an outeritis also in scope, causing confusing shadowing; naming the parameter explicitly avoids this. - Trying to use
itin a lambda that takes more than one parameter;itonly works for exactly one implicit parameter. - Overusing
itin long or complex lambdas where a named parameter would make the code much easier to read.
- When a lambda has exactly one parameter and its type can be inferred, that parameter can be referred to implicitly as
it. itonly applies to single-parameter lambdas; multi-parameter lambdas must name all their parameters explicitly.- Nested lambdas that both rely on implicit
itcan 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: