Higher-order functions
A higher-order function is a function that takes at least one function as an argument, or returns a function as its result. It is fully supported in Kotlin, as functions are first-class citizens. Let's look at it in an example. Let's suppose that we need two functions: a function that will add all BigDecimal numbers from a list, and a function that will get the product (the result of multiplication between all the elements in this list) of all these numbers:
fun sum(numbers: List<BigDecimal>): BigDecimal {
var sum = BigDecimal.ZERO
for (num in numbers) {
sum += num
}
return sum
}
fun prod(numbers: List<BigDecimal>): BigDecimal {
var prod = BigDecimal.ONE
for (num in numbers) {
prod *= num
}
return prod
}
// Usage
val numbers = listOf(
BigDecimal.TEN,
BigDecimal.ONE,
BigDecimal.valueOf(2)
)
...