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.

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.
now let’s define a conditioning method
  
fun isMultipleOf (number: Int, multipleOf : Int): Boolean{
return number % multipleOf == 0
}
the above method checks if the passed first argument is a multiple of another passed argument and returns a Boolean value.

Now let’s call the higher-order function with this condition
  
var list = arrayListOf<Int>()
for (number in 1..10){
list.add(number)
}
var resultList = list.filterOnCondition { isMultipleOf(it, 5) }
The above code will filter the list object with the multiples of 5 and returns a new ArrayList object having 5 and 10 in it.

The last line of above code can be replaced with Lambda expression also.

The below two lines will do the same as the last line of above code snippet doing.
  
var resultList = list.filterOnCondition { it -> it % 5 == 0 }
or
var resultList = list.filterOnCondition { it % 5 == 0 }

The same method can be called for any other data type also.
  
var listOfStr = arrayListOf<String>()
listOfStr.add("Hello")
listOfStr.add("World")
listOfStr.add("How")
listOfStr.add("are")
listOfStr.add("you")

var modifiedList = listOfStr.filterOnCondition { it.contains("e") }
In this case the modifiedList will be an ArrayList of String type having two object “Hello” and “are” in it.