Kotlin Higher-Order Functions
Overview
Higher-order functions are a common concept in functional programming.
A function is called a higher-order function if it satisfies one or more of the following.
- It receives one or more functions as arguments.
- It returns a function as its result.
This satisfies two of the three conditions for a first-class function. All other functions that do not satisfy these conditions are called first-order functions.
In other words, it can be described as a function that creates functions.
Representative higher-order functions include map, filter, reduce, and lambda.
Higher-Order Function
The following example receives a function as an argument and returns a function as the result.
fun returnParamFunc(func: () -> String): () -> String {
return func
}
fun main() {
val hello: () -> String = { "Hello world!" }
val returned = returnParamFunc(hello)
print("${returned()}")
}
Output:
Hello world!
In the example above, the returnParamFunc function receives hello as an argument and returns that function again. The returned function printed "Hello world!".
Arguments and Return Types
fun returnParamFunc(func: () -> String): () -> String {
return func
}
When passing a function as an argument, you must specify the function type after the function variable name, such as : () -> String.
A function that receives an Int as an argument and returns a String is written as (Int) -> String. The type in parentheses on the left side of -> ((Int)) is the argument, and the type on the right side of -> (String) is the return type.
If two Int values are passed as arguments, write (Int, Int) -> String. If more arguments are needed, add more argument types. If there are no arguments, write only empty parentheses, as in () -> String.
If there is no return value, use Unit, as in (Int, Int) -> Unit.