lambda

How should I pass a lambda function as a parameter to another function in Android using Kotlin


I am trying to use a lambda method which will add two numbers and I am trying to pass that method as a parameter to another method. But I am unable to achieve this. Could anyone please help me out on this?

Not only Int, I also need understanding of how to use Strings here as well.


Solution

  • Let’s assume, you’re trying to add two integers and it is returning a result, which is also an integer of course. In Kotlin, we can simply create a lambda function as the following:

    fun addTwoNumbers(): (Int, Int) -> Int = { first, second -> first + second }
    

    This means, the addTwoNumbers() will accept two Int parameters and it will also return an Int type. Let’s now break this down for better understanding:

    Also, notice how we have used the curly braces { }.

    This is how lambdas are defined, and the functionality of that lambda is provided inside the curly braces, like this: {first, second -> first + second}.

    Now let’s create another method which will accept lambda as a parameter, like below:

    fun sum(  
        x: Int,  
        y: Int,  
        action: (Int, Int) -> Int // Notice how we are passing the lambda as a parameter to sum() method. 
    ) = action(x, y)
    

    These type of functions are also known as Higher Order Functions.

    Now, we can simply use it like the following:-

    fun main() {
        val summation = sum(10, 20, addTwoNumbers())
        println(summation)
    }
    

    This will print 30 in the console.