Instruction
Lambda Expressions
In Kotlin, a lambda expression is a function without a name. It’s used to define a code block that can be passed as an argument to a function or stored in a variable.
Defining a Lambda Expression
To define a lambda expression, you enclose a block of code in curly braces: {}. Then, you can assign the code block to a variable, such as the following:
val myFirstLambda = { println("This is my first lambda") }
The code above has two parts: a variable, myFirstLambda, on the left and a lambda expression on the right.
Now, you call the lambda from the main() function:
fun main() {
myFirstLambda()
}
When you run this code, it prints the following on the screen:
This is my first lambda
You call a lambda just like you call a regular function. When you call the lambda it will ultimately execute the code in the curly braces. Neat!
Lambda Expressions With Arguments
A lambda expression can take arguments and return a value. The syntax of a lambda expression taking two arguments of type Int looks like this:
The last expression of the code enclosed in the curly braces is the value that will be returned when the lambda is executed. For example:
val myLambda = { num1: Int, num2: Int ->
val sum = num1 + num2
// The value stored in sum is the value that will be returned when the `myLambda` lambda expression is executed since it's the last statement in the lambda.
sum
}
Type Inference
Kotlin’s type inference enables the compiler to evaluate the type of a lambda, such as in the myLambda expression:
val myLambda = { num1: Int, num2: Int ->
val sum = num1 + num2
sum
}
The type of the lambda is evaluated to (Int, Int) -> Int, meaning it takes two parameters of type Int and has a return type of Int.
Sometimes, the compiler can’t infer all of the types in a lambda. In such cases, you must declare the type for the lambda expression yourself. An example of this is a lambda expression that takes an argument of type String and returns an Int. You write it like this:
val stringLambda: (String) -> Int = { name: String ->
name.length
}
If a lambda expression does not return a value, specify Unit as the return type.
You’ve learned about lambda functions and the syntax of defining a lambda. Now, it’s time to create and call lambda functions in a demo.