DEV Community

Jens Klingenberg
Jens Klingenberg

Posted on

4 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More