18

Higher Order Functions in Kotlin with Example

 3 years ago
source link: https://www.simplifiedcoding.net/higher-order-functions-kotlin/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Higher Order Functions in Kotlin with Example

This post is about Higher Order Functions in Kotlin.

One of the cool thing about Kotlin is; it has support of functional programming as well. That means kotlin functions can be stored in a variable, passed to other function as argument and also can be returned from a function.

What are Higher Order Functions in Kotlin?

As I said in Kotlin we can store functions in variables, we can pass them as argument to other functions and we can also return function from a function. When we define a function that accepts a function as an argument or returns a function from it we call it a Higher Order Function.

Sounds confusing? 😉

Here is an example for you.

Defining a Higher Order Function

Here is a simple Higher Order Function.

//A simple Higher Order Function in Kotlin
//This function accepts three parameters
//And the last parameter is a function
fun rollDice(
        range: IntRange,
        time: Int,
        callback: (result: Int) -> Unit
    for (i in 0 until time) {
        val result = range.random()
        //As the last parameter is a function
        //we can call it as a function
        callback(result)

Let’s understand the third parameter in the above given function.

Higher Order Functions in Kotlin
Function as a Parameter

The above picture explains, how you can define function as a parameter. Now we will try to call this function.

Calling a Higher Order Function

Now, let’s call our higher order function.

fun main() {
    rollDice(1..6, 3, { result ->
        println(result)

We will get the following output.

Let’s understand how we pass a function as a parameter.

Higher Order Functions in Kotlin - 1
Passing function as an argument

In the above picture we are using the following snippet to pass the third parameter for the function rollDice()

{ result ->
    println(result)

And this is called a lambda expression. And we can even store it to a variable.

    val a: (result: Int) -> Unit = { result ->
        println(result)

Trailing Lambda

In our example, the function rollDice()  is the higher order function that is accepting another function as an argument. And the function that we have defined as the argument is the last parameter. When we have this situation, we can put the lambda expression outside the parenthesis while calling the function.

fun main() {
    rollDice(1..6, 3) { result ->
        println(result)

Looks cool right?

it Keyword

Another interesting thing is, when we have only a single parameter in our lambda expression, we can omit the parameter name and instead of writing a name we can use it keyword to get the parameter.

fun main() {
    rollDice(1..6, 3) {
        println(it)

Another cool feature correct?

Now, another interesting thing I would like to tell is; when your function is having only a single parameter that is a function, in this case you can even omit the parenthesis.

fun rollDice(callback: (result: Int) -> Unit) {
    callback((1..6).random())
fun main() {
    rollDice {
        println(it)

Assigning null as the default value

We can also assign null as the default value.

fun rollDice(callback: ((result: Int) -> Unit)? = null) {
    callback?.invoke((1..6).random())
fun main() {
    rollDice {
        println(it)

When you have null as the default value, you can use invoke()  to call the function.

Awesome right? Or you are still confused?

If you are still confused, you might be thinking that why to make things complicated. But trust me it is a very handy and useful thing.

Imagine a scenario when you are doing some heavy operation (that requires long time to execute) in a different thread inside a function. And after finishing that task you need a callback. You can achieve this thing very easily using higher order functions in kotlin.

fun rollDice(callback: ((result: Int) -> Unit)? = null) {
    println("Roll Dice Started")
    thread {
        //mimicking a heavy operation
        //by just putting a Thread.sleep
        Thread.sleep(5000)
        //function was already finished
        //but after 5 seconds
        //we will get a callback at the trailing lambda
        callback?.invoke((1..6).random())
    println("Roll Dice Ended")
fun main() {
    rollDice {
        println(it)

Try running this code in your machine.

So that’s all for Higher Order Functions in Kotlin. In case you have some inputs to improve this post, then please comment it below. Questions are welcome. Please share this post with your friends if you think it was useful. Thank You.

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.

Checkout these tutorials as well:

  • Tic Tac Toe Android App Tutorial with MiniMax Algorithm
  • Android Upload File to Server with Progress using Retrofit
  • Firebase MVVM Example - Implementing Authentication
  • Android Custom Dialog Example - Making Custom AlertDialog
  • Mailgun Android Example: Sending Emails with Mailgun
  • Bottom Navigation Android Example using Fragments

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK