0
0
Kotlinprogramming~5 mins

It keyword for single parameter in Kotlin

Choose your learning style9 modes available
Introduction

The it keyword helps you write shorter code when a function has only one parameter.

When you use a lambda function with one parameter and want to keep code simple.
When you want to avoid naming the single parameter explicitly in short functions.
When working with collections and using functions like <code>map</code>, <code>filter</code>, or <code>forEach</code>.
When you want to quickly transform or check items in a list without extra code.
Syntax
Kotlin
collection.map { it * 2 }

it automatically refers to the single parameter inside the lambda.

You don't need to declare the parameter name if there is only one.

Examples
This doubles each number in the list using it as the current item.
Kotlin
val numbers = listOf(1, 2, 3)
val doubled = numbers.map { it * 2 }
Here, it is each word, and we get the first letter.
Kotlin
val words = listOf("apple", "banana", "cherry")
val firstLetters = words.map { it.first() }
This keeps only numbers greater than 1 using it.
Kotlin
val filtered = numbers.filter { it > 1 }
Sample Program

This program triples each number in the list using it and prints the new list.

Kotlin
fun main() {
    val numbers = listOf(5, 10, 15)
    val tripled = numbers.map { it * 3 }
    println(tripled)
}
OutputSuccess
Important Notes

If your lambda has more than one parameter, you cannot use it.

You can always name the parameter explicitly if you want, like { number -> number * 2 }.

Summary

it is a shortcut for the single parameter in a lambda.

Use it to write cleaner and shorter code when working with one parameter.

Commonly used with collection functions like map and filter.