Jens Klingenberg

Higher Order Functions in Kotlin

Posted on March 27, 2018  •  2 minutes  • 307 words
Table of contents
A higher-order function is a function that can take other functions as parameters and returns other functions.

How to create a Higher Order Function?

```kotlin fun printIt(passedFunction: () -> Unit ) { passedFunction() println("bye, world!") } ```

You can create a higher order function like any other function in Kotlin, but you need to create an parameter that has a function as the type. As you can see above my printIt() method has a parameter named “passedFunction” of the type “()”, which means that it’s a function. “→ Unit” is the return value of the function that is passed in printIt(). For a example if you would have a function with the parameter “function: ()→Boolean” you could only pass in functions which return an Boolean Value.

To execute “passedFunction” you need to use round brackets after the function name, so “passedFunction()”. Without the brackets the “passedFunction” will still be of type function and can be passed to further functions.

How to call a Higher Order Function?

fun main(args: Array<String>) {
    printIt{
      print("Hello World")
    }
}

fun printIt(passedFunction: ()->Unit ) {
  passedFunction()
  println("bye, world!")
}

You use the function like any other Kotlin function, but you use braces instead of round brackets. Everything that is inside printIt{} will then be passed to the method printIt() and will be executed wherever the passed function is called.

Other Example:

fun runInBackground(function: () -> Unit) {
  Observable.fromCallable {
    function()

    true
  }
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe { result ->
            //Use result for something
    }
}

On Android i’m using this function in combination with RxJava to run functions outside of the MainThread. I just need to wrap runInBackground{} around the functions, that should run in the background and i can avoid using things like AsyncTask.

Resources

Kotlin Reference Higher Order Functions

You can try the first example in a browser on Try Kotlin  

Let's connect: