DEV Community

Jens Klingenberg
Jens Klingenberg

Posted on

Higher Order Function in Kotlin

Note: This post was originally published on my blog.

What is a Higher Order Function?

A higher-order function is a function that can take other functions as parameters and returns other functions.

fun printIt(passedFunction: ()->Unit ) {
passedFunction()
println("bye, world!")
}
view raw printIt hosted with ❤ by GitHub

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?

printIt{
print("Hello World")
}
view raw gistfile1.txt hosted with ❤ by GitHub

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
}
}
view raw runInBackground hosted with ❤ by GitHub

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

Top comments (0)

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay