How to Return Value from Lambda Function in Kotlin?
In Kotlin, lambda functions can have return values just like regular functions. This allows you to perform operations and return results directly within the lambda body. Let’s explore how to use lambda functions with return values with examples.
Example 1: Simple Lambda Function with Returns Sum of Two Numbers
Step 1: Define a Lambda Function
Create a lambda function that takes two parameters and returns their sum.
val sum: (Int, Int) -> Int = { a, b -> a + b }
Step 2: Invoke the Lambda Function
Invoke the lambda function by passing arguments to it.
val result = sum(5, 3)
println("Sum: $result")
Complete Kotlin Program
Following is the complete Kotlin program demonstrating the use of lambda functions with return values.
Kotlin Program
fun main() {
val sum: (Int, Int) -> Int = { a, b -> a + b }
val result = sum(5, 3)
println("Sum: $result")
}
Output
Example 2: Lambda Function with Conditional Return Value
Step 1: Define a Conditional Lambda Function
Create a lambda function that checks if a number is even and returns a boolean value.
val isEven: (Int) -> Boolean = { number -> number % 2 == 0 }
Step 2: Invoke the Lambda Function
Invoke the lambda function to check if a number is even.
val number = 10
val even = isEven(number)
println("Is $number even? $even")
Complete Kotlin Program
Following is the complete Kotlin program demonstrating the use of lambda functions with return values.
Kotlin Program
fun main() {
val isEven: (Int) -> Boolean = { number -> number % 2 == 0 }
val number = 10
val even = isEven(number)
println("Is $number even? $even")
}
Output
Summary
Lambda functions in Kotlin can have return values, allowing you to perform computations and return results directly within the lambda body. This provides a concise and expressive way to define functionality.