Passing a function as a parameter to another
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 more easy to work with. In fact, many of the Kotlin library’s functions are high order, such as map
. In Kotlin, we can declare functions and function references as values that are then passed in to the function. In this section, we will first understand how to declare lambdas and then how to pass them into a function.
Getting ready
You need to install a preferred development environment that compiles and runs Kotlin. You can also use the command line for this purpose, for which you need Kotlin compiler installed, along with JDK. I am using an online IDE at https://try.kotlinlang.org/ to compile and run my Kotlin code for this recipe. You can also use IntelliJ IDEA as the development environment.
How to do it...
Let's follow these steps to understand the working...