A higher-order function accepts a function as an argument, returns a function, or does both. In Kotlin, those function values can be lambdas or function references. This lets code parameterize behavior rather than hardcode it, helping remove duplication and create focused abstractions. section 10.1 section 10.0
Pass an operation
Declare a function type for the behavior you need, then invoke the parameter like an ordinary function. Different lambdas supply addition or multiplication without changing `twoAndThree`. ```kotlin fun twoAndThree(operation: (Int, Int) -> Int) { val result = operation(2, 3) println("The result is $result") } twoAndThree { a, b -> a + b } // 5 twoAndThree { a, b -> a * b } // 6 ``` section 10.1.2
Listing 10.2 Implementing a simple version of the filter function
fun String.filter(predicate: (Char) -> Boolean): String {
return buildString {
for (char in this@filter) { #1
if (predicate(char)) append(char) #2
}
}
}
fun main() {
println("ab1c".filter { it in 'a'..'z' }) #3
// abc
}
A predicate is a function value whose `Boolean` result controls whether each character is appended. The same shape generalizes to collection filtering. section 10.1.2
Functions can also produce behavior for later use. A shipping-cost factory selects and returns an `(Order) -> Double` calculator; a contact filter factory returns a `(Person) -> Boolean` predicate based on current UI settings. Returning a function decouples selection logic from the code that applies the selected behavior. section 10.1.5
Use higher-order functions when varying behavior is the part worth extracting:
- Replace repeated conditions with a predicate parameter, such as computing average visit duration for arbitrary operating-system and path criteria. section 10.1.6
- Represent Strategy pattern alternatives as lambdas instead of an interface and multiple strategy implementations. section 10.1.6
- Build reusable component-level utilities and general-purpose libraries around function-typed parameters or return values. section 10.4
A function type can describe a variable, parameter, or return value that holds a function reference. Parameter names in a function type improve readability and IDE completion, but do not affect type matching. Higher-order functions can have lambda-related overhead; inline functions can remove that overhead and enable non-local returns, while anonymous functions provide different return behavior for blocks with multiple exits. section 10.1.2 section 10.4













