Kotlin Lambda Functions
In Kotlin, lambda functions are used to define anonymous functions or function literals in a concise way.
Lambda functions are often used for short, one-off operations, and they can be passed as arguments to higher-order functions or stored in variables.
The following is a simple example for a lambda function, that takes two integer values, and returns their sum. And we are assigning this lambda function to a variable, sum
.
val sum: (Int, Int) -> Int = { x, y -> x + y }
(Int, Int)
states that the lambda function takes two integer values.-> Int
states that the return value of the lambda function is an integer value.x, y
is where the arguments are stored.-> x + y
is the return value.
Let us see how to use this lambda function in a program, to find the sum of two numbers.
Kotlin Program
val sum: (Int, Int) -> Int = { x, y -> x + y }
fun main() {
println(sum(5, 10)) //15
println(sum(100, 200)) //300
}
Output
Lambda function with multiple statements
Lambda functions can have a body with multiple expressions. The last expression in the lambda body is implicitly treated as the return value.
Kotlin Program
val sum: (Int, Int) -> Int = { x, y ->
val result = x + y
result
}
fun main() {
println(sum(5, 10))
println(sum(100, 200))
}
Output
Lambda functions with single parameter
For lambda functions with a single parameter, you don’t have to explicitly name it. Instead, you can use the implicit it
variable.
In the following program, we define a lambda function that takes a string, and returns the first three characters.
Based on the syntax that we shown at the starting of this tutorial, the function could be as shown in the following.
val firstThree: (String) -> String = { x -> x.take(3)}
To make it more concise, we can use it
keyword, as shown in the following.
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
Related Tutorials
The following tutorials cover some more specific scenarios covering Lambda Functions.