Jens Klingenberg
Posted on March 31, 2018
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.
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?
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:
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
Posted on March 31, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 21, 2024