Introduction
The it keyword helps you write shorter code when a function has only one parameter.
The it keyword helps you write shorter code when a function has only one parameter.
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.
it as the current item.val numbers = listOf(1, 2, 3) val doubled = numbers.map { it * 2 }
it is each word, and we get the first letter.val words = listOf("apple", "banana", "cherry") val firstLetters = words.map { it.first() }
it.val filtered = numbers.filter { it > 1 }
This program triples each number in the list using it and prints the new list.
fun main() { val numbers = listOf(5, 10, 15) val tripled = numbers.map { it * 3 } println(tripled) }
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 }.
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.
it keyword represent in a Kotlin lambda with a single parameter?itit automatically refers to that single parameter inside the lambda.it = single lambda parameter [OK]it means the one lambda input [OK]it is a loop variableit with a keyword to declare variablesit prints outputit in a Kotlin lambda that doubles each number in a list?map has one parameter, so it can be used implicitly.list.map { it * 2 } correctly uses it without naming the parameter explicitly.it only when lambda has one parameter [OK]it togetherval numbers = listOf(1, 2, 3)
val result = numbers.filter { it > 1 }
println(result)it > 1, so only numbers greater than 1 remain.it > 1 = [2, 3] [OK]it meets condition [OK]val list = listOf(1, 2, 3)
val doubled = list.map { it * }
println(doubled)it * is incomplete; it lacks a value after the multiplication operator.*.it * is valid aloneit must be declared explicitlyval words = listOf("apple", "banana", "cat"), which Kotlin code uses it correctly to create a list of word lengths greater than 3?words.filter { it.length > 3 }, correctly filters the words list to include only words with length greater than 3, using it properly.it.length > 3 to get words longer than 3 [OK]it incorrectly in filterPass the test and this pattern moves unknown