Introduction
While writing code, we may encounter code that looks like a function but doesn't have a fun keyword to declare it as a function.
These are called Lambda Expressions, and they are widely used in Android Development.
In this article, we will learn about Kotlin Lambda Expression and its need to use them. But before jumping into Lambda, we would strongly recommend learning about Kotlin Functions.
What is Lambda?
Lambda are one of the types of function literals. They are extensively used as a function not defined by a fun keyword, whereas used as part of an expression. As these functions don't require a name, we can use them to assign variables and use them as a function parameter.
Let’s try to explain this with an example.
fun main() {
val lambda = { println("Hello Kotlin!") }
lambda()
}
Here, we have assigned a Unit type (equivalent to void in Java) to lambda variable, which will print Hello Kotlin!
In short, we can assume that lambda has a value that will print Hello Kotlin!, and we write lambda() for calling this variable.
Now, let us look into another example of lambda expression.
fun main() {
val sum: (Int, Int) -> Int = { n1: Int, n2: Int -> n1 + n2 }
println(sum(5,6))
}
Here we have a sum variable with two Integer type parameters that we will pass while calling this variable. This variable will return the Integer type value as the output.
Output:
11
Here we have supplied 5 and 6 as two parameters in the sum variable and the lambda expression. We are using these two values and returning their sum.
So, after discussing the above example, we can conclude that the syntax of lambda expression would be

Source programiz
val lambda : return_type = { input_argument_list -> do_something_with_input }
Here, there is something to note about lambdas expression. Curly brackets are always used to wrap a lambda expression. Code body is always followed by -> symbol. Defining the data type of the lambda is optional.
val sum: (Int, Int) -> Int = { n1, n2 -> n1 + n2 }
Here, we have eliminated the Argument Datatype Declaration in the above example.
Lambdas can be puzzling at times because they can be written and utilized in a variety of ways, making it difficult to determine whether something is a lambda or not. The following snippet is an example of this:
fun main() {
val filterArr = listOf(1, 2, 3, 4, 5, 6,7,8,9,10).filter({ it % 2 == 0 })
println(filterArr)
}
This example filters out even numbers from the numbers from 1 to 10. Here we have used it operator, a simple parameter passing to the expression. Here we are iterating through each number in the given list to represent that number.
Output:
[2, 4, 6, 8, 10]





