Higher-order functions in Kotlin

What is a higher-order function?

In Kotlin, a function can be passed as a parameter or can be returned from a function, the function which does the same is known as a higher-order function. In other words, a higher-order function is a function that takes functions as parameters or returns a function.

This post was originally posted at https://agrawalsuneet.github.io/blogs/higher-order-functions-in-kotlin/ and reposted on Medium on 7th Nov 2017.

Let’s take an example

fun <T> ArrayList<T>.filterOnCondition(condition: (T) -> Boolean): ArrayList<T>{
val result = arrayListOf<T>()
for (item in this){
if (condition(item)){
result.add(item)
}
}

return result
}

in the above code,

<T>
this defines the template type over which the operation will be performed. There can be multiple templates defined separated by “,“ which can be used within the same higher-order function. The multiple template definition will look like <T, R, S>

ArrayList<T>.filterOnCondition
this defines the method name as filterOnCondition which be called on an ArrayList object of the template class.

condition: (T) -> Boolean
this defines a method which filterOnCondition accepts as an argument. That method name is denoted as ‘condition’ which takes the template class object as an argument and return a Boolean object.

: ArrayList<T>
this defines the return type of this(filterOnCondition) function which is an object of ArrayList of the template class in this case.

{
val result = arrayListOf<T>()
for (item in this){
if (condition(item)){
result.add(item)
}
}

return result
}

this defines the body of the higher-order function which creates a new object of ArrayList of the template class and on each element of calling ArrayList object, it calls the condition method based on which it add the same item in result ArrayList and returns the result object.

Please continue reading at https://agrawalsuneet.github.io/blogs/higher-order-functions-in-kotlin/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.