How to Pass a Function as a Parameter to Another in Kotlin?
Kotlin gives us the power to declare high-order functions. In a high-order function, we can pass and return functions as parameters. This is an extremely useful feature and makes our code much easier to work with. In fact, many of the Kotlin library’s functions are high order, such as NBQ. In Kotlin, we can declare functions and function references as values that are then passed into the function. We will first understand how to declare lambdas and then how to pass them into a function.
Let’s start by understanding how we declare functions as lambdas:
In the preceding code block, we declared two lambdas: one (funcMultiply) that takes two integers and returns an integer, and another (funcSayHi) lambda that takes a string and returns a unit-that is, it returns nothing. Although we did not need to declare the type of arguments and the return type in the preceding example, in some cases we need to explicitly declare the argument types and return types. We do this in the following way:
So now that we have a general idea of how lambdas work, let’s try and pass one in another function-that is, we will try a high-order function. Check out this code snippet:
It is as simple as that-create a function lambda and pass it into the function. So this is just one aspect of a high-order function-that is, we can pass a function as an argument to the function. Another use of high-order functions is to return a function. Consider the following example where we need a function that transforms the total price of an order according to certain conditions. Kind of like an e-commerce site, but way simpler
Note how we need to change functions that we apply based on certain conditions so that we return a function that suits the conditions. We assign the returned function to a variable and then we can just put append () in front of the variable to use it as a function, just like we did with the lambdas. This works because the high-order function is essentially returning a lambda.
In Kotlin, we can assign a function to a variable, and then we can pass it into a function or return it from a function. This is because it’s essentially declared like a variable. This is done using a lambda declaration of functions.
Please Login to comment...