Higher-Order Functions
A higher-order function is a function that takes another function as parameter and/or returns a function.
Taking Functions as Parameters
fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int { // 1
return operation(x, y) // 2
}
fun sum(x: Int, y: Int) = x + y // 3
fun main() {
val sumResult = calculate(4, 5, ::sum) // 4
val mulResult = calculate(4, 5) { a, b -> a * b } // 5
println("sumResult $sumResult, mulResult $mulResult")
}
- Declares a higher-order function. It takes two integer parameters,
x
andy
. Additionally, it takes another functionoperation
as a parameter. Theoperation
parameters and return type are also defined in the declaration. - The higher order function returns the result of
operation
invocation with the supplied arguments. - Declares a function that matches the
operation
signature. - Invokes the higher-order function passing in two integer values and the function argument
::sum
.::
is the notation that references a function by name in Kotlin. - Invokes the higher-order function passing in a lambda as a function argument. Looks clearer, doesn't it?
Returning Functions
fun operation(): (Int) -> Int { // 1
return ::square
}
fun square(x: Int) = x * x // 2
fun main() {
val func = operation() // 3
println(func(2)) // 4
}
- Declares a higher-order function that returns a function.
(Int) -> Int
represents the parameters and return type of thesquare
function. - Declares a function matching the signature.
- Invokes
operation
to get the result assigned to a variable. Herefunc
becomessquare
which is returned byoperation
. - Invokes
func
. Thesquare
function is actually executed.