Kotlin Lambda it

Kotlin Lambda it

In Kotlin, when a lambda function has a single parameter, then you can use it keyword as the parameter name, without explicitly naming the parameter.

For example, to find the square of a given integer, instead of using the following lambda notation,

val square: (Int) -> Int = { num -> num * num}

you can use the following notation, which is way more concise.

val square: (Int) -> Int = { it * it}

Example 1: Finding square of integer using “it” in Lambda function

In the following program, we define a lambda function that takes an integer, and returns its square.

val square: (Int) -> Int = { it * it}

Let us use the above lambda function in a program, and observe the output.

Kotlin Program

val square: (Int) -> Int = { it * it}

fun main() {
    println(square(5))    //25
    println(square(7))    //49
}

Output

25
49

Example 2: Getting the first three characters in string using “it” in Lambda function

In the following program, we define a lambda function that takes a string, and returns the first three characters.

val firstThree: (String) -> String = { it.take(3)}

Let us use the above lambda function in a program, and observe the output.

Kotlin Program

val firstThree: (String) -> String = { it.take(3)}

fun main() {
    println(firstThree("apple"))
    println(firstThree("banana"))
}

Output

app
ban