user16647620
user16647620

Reputation:

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.

Upvotes: 2

Views: 4017

Answers (1)

Sayan Subhra Banerjee
Sayan Subhra Banerjee

Reputation: 291

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 2 Int parameters and it will also return an Int type.

Let’s now break this down for better understanding:

(Int, Int) : this denotes the addTwoNumbers() will accept 2 Int parameters.

-> (Int) : this denotes the addTwoNumbers() will return an Int value as a result.


Also notice how we have used the parenthesis { }.

This is how lambdas are defined and the functionality of that lambda is provided inside the parenthesis, 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)

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(10, 20, addTwoNumbers())
    println(summation)
}

This will print 30 in the console.

Upvotes: 5

Related Questions