liveBook · Manning

Higher-order function

As explained in Kotlin in Action, 2E

A higher-order function is a function that accepts functions as arguments, returns functions, or both.

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

How Kotlin in Action, 2E covers it

How deep it goes
Defines argument- and return-based forms, implements custom filters, and relates performance and return-control details to inline and anonymous functions.
Examples
Demonstrates arithmetic operations, string filtering, shipping calculators, contact predicates, and site-visit duration analysis.
What it assumes
Builds on lambdas and function references while introducing function types needed to declare higher-order functions.
What you can do after
Build it from scratch by declaring function-typed parameters or returns and supplying behavior as lambdas.
How it connects
Connects function types, lambdas, function references, predicates, inline functions, anonymous functions, and the Strategy pattern.

Also explained in

Compare how 14 books explain higher-order function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.