0

Unable to understand how to return a lambda from a method. Anyone’s help will be appreciated!

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for this detailed answer! It's now crystal clear to me. Thank you once again.
Happy coding! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.