it
- Kotlin course
- Intermediate
- Lesson 55/116
- 5 min
Learn single-parameter lambdas with it.
it
When a lambda has a single parameter, you can use it instead of writing the parameter name. Kotlin infers it automatically.
Example: val square: (Int) -> Int = { it * it }. Here it stands for the single parameter. Calling square(5) returns 25. Using it keeps code short; but with multiple parameters or when readability drops, an explicit name is preferred. listOf(1,2,3).map { it * 2 } is a common use of it.
Using it
it is especially common in collection methods. Methods like map, filter and forEach take a single-parameter lambda.
Example: listOf(1, 2, 3).map { it * 2 } doubles each element and returns [2, 4, 6]. listOf(1, 2, 3).filter { it > 1 } keeps the larger ones and returns [2, 3]. Using it keeps code short. In nested lambdas it can clash; in that case, use an explicit parameter name.
Practice square and map with it
Declare val square: (Int) -> Int = { it * it }. In main call println(square(5)) and println(listOf(1, 2, 3).map { it * 2 }) on separate lines.
Starter code
// a square lambda using it
// call square and map in main
// print both results on separate linesSample solution
val square: (Int) -> Int = { it * it }
fun main() {
println(square(5))
println(listOf(1, 2, 3).map { it * 2 })
}Expected output
25 [2, 4, 6]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the lambda with it
val square: (Int) -> Int = { ____ * it }
val square: (Int) -> Int = { it * it }
Explanation: it stands for the parameter in a single-parameter lambda.
2 Match the it usage
| Term | Meaning |
|---|---|
{ it * it } |
Single-parameter lambda |
{ it * 2 } |
map body |
{ it > 1 } |
filter body |
listOf(...).map |
Collection call |
3 When is <code>it</code> used?
- In multi-parameter lambdas
- Inside a class
- In single-parameter lambdas Correct answer
- Only with fun
Explanation: it is used in single-parameter lambdas.