0
0
KotlinConceptBeginner · 3 min read

What is the it keyword in lambda Kotlin and How It Works

In Kotlin, the it keyword is an implicit name for a single parameter in a lambda expression when the parameter type can be inferred. It lets you write shorter and cleaner lambdas without explicitly naming the parameter.
⚙️

How It Works

Imagine you are giving instructions to a friend, but you don't want to keep repeating the person's name. Instead, you just say "it" to mean the person you're talking about. In Kotlin lambdas, it works the same way. When a lambda has only one parameter, Kotlin automatically gives that parameter the name it, so you don't have to write it yourself.

This makes your code shorter and easier to read, especially when the parameter's meaning is clear from the context. You can think of it as a placeholder that Kotlin fills in for you, so you can focus on what you want to do with the value rather than naming it.

💻

Example

This example shows a list of numbers where we use a lambda to print each number multiplied by 2. We use it to refer to each number without naming the parameter explicitly.

kotlin
fun main() {
    val numbers = listOf(1, 2, 3, 4)
    numbers.forEach { println(it * 2) }
}
Output
2 4 6 8
🎯

When to Use

Use it in lambdas when there is only one parameter and its meaning is clear from the context. This helps keep your code concise and readable.

For example, when working with collections like lists or maps, you often pass lambdas to functions like map, filter, or forEach. Using it makes these operations simpler and cleaner.

If your lambda has more than one parameter or if the meaning of the parameter is unclear, it's better to name the parameters explicitly for clarity.

Key Points

  • it is an implicit name for a single lambda parameter in Kotlin.
  • It helps write shorter and cleaner lambda expressions.
  • Only available when the lambda has exactly one parameter.
  • Use it when the parameter's meaning is obvious from context.
  • For multiple parameters, you must name them explicitly.

Key Takeaways

it is the default name for a single lambda parameter in Kotlin.
Use it to write concise lambdas when there is only one parameter.
Avoid it if the parameter meaning is unclear or if there are multiple parameters.
Using it improves readability in simple lambda expressions.
Explicit parameter names are better for complex lambdas with multiple inputs.