Unable to understand how to return a lambda from a method. Anyone’s help will be appreciated!
1 Answer
Suppose, you’re trying to add two integers and will return an integer result.
In Kotlin, we can simply create a normal function like this:
fun addTwoNumbers(first: Int, second: Int): Int = first + second
Now let’s create another method which will return a lambda, like the following:
fun sum(): (Int, Int) -> Int = { x, y -> addTwoNumbers(x, y) }
As you can see, the return type of sum() is (Int, Int) -> Int, which means this is returning a lambda.
And for creating lambdas, we will simply use { } and will write the function body inside these parenthesis, like this: { x, y -> addTwoNumbers(x, y) }
This type of functions are also known as Higher Order Functions.
Now, we can simply use it like the following:-
fun main() {
val summation = sum()
println(summation(100, 300))
}
This will print 400 in the console.