Explain it simply
Higher-order functions in plain language
A higher-order function is a function that takes another function as an input, or hands one back. Instead of asking 'give me the numbers', you say 'give me the numbers, and here is the rule for which ones to keep'. Kotlin's collection functions are the best-known examples: filter keeps, map transforms, fold combines.
Think of a sorting machine at a post office. It knows how to move parcels along a belt and drop each one into a bin, but it knows nothing about your rules. Hand it a card that says 'send parcels over 5 kg to bin B' and it applies the card to every parcel. The machine is the higher-order function and the card is the lambda.
Problem → Why → Solution
The problem: four questions, four loops
You have a list of orders and your manager asks four questions on the same afternoon: which orders are paid, what the revenue is, how much each customer spent, and who the biggest spenders are. With plain loops you write four loops, four mutable result variables and four chances to forget to reset one of them. Worse, the loops do not say what they compute; the reader must read each body to discover that this one sums and that one filters.
A chain of small steps solves both problems, but it raises two new worries: does a long chain create a pile of temporary lists, and is a lambda called on every element slower than a loop? The answers come later in this lesson.
data class Order(val customer: String, val total: Double, val paid: Boolean)
fun main() {
val orders = listOf(Order("Ada", 120.0, true), Order("Linus", 35.5, false))
var revenue = 0.0
for (o in orders) {
if (o.paid) revenue += o.total
}
val perCustomer = mutableMapOf<String, Double>()
for (o in orders) {
if (o.paid) perCustomer[o.customer] = (perCustomer[o.customer] ?: 0.0) + o.total
}
println("revenue=$revenue perCustomer=$perCustomer")
}Describe the result, not the bookkeeping
Higher-order functions move the bookkeeping into the library. filter, groupBy and fold already contain the loop and the accumulator, so your code states the rule and nothing else. The two worries are real but manageable: a lambda passed to an inline function is copied into the call site and costs nothing extra, and a Sequence avoids temporary lists when a chain is long or the data is large. Both are covered below.
Core concept: taking functions, returning them and chaining
A function is higher-order when one of its parameters has a function type or when it returns a function. The declaration fun <T> List<T>.countWhere(test: (T) -> Boolean): Int says 'give me a test that takes a T and answers yes or no'. Inside the body you call test(item) like any function. The caller supplies the rule with a trailing lambda: orders.countWhere { !it.paid }.
The standard library already offers the functions you need most. filter keeps the elements for which the lambda returns true. map replaces each element by the lambda's result, so the list keeps its length. fold walks the list with an accumulator that starts from a value you choose, and reduce does the same but starts from the first element. groupBy builds a Map from a key the lambda computes to the list of elements with that key. sortedBy and sortedByDescending order elements by a key, and associate, associateBy and associateWith build maps out of a list.
| Function | The lambda receives | Result |
|---|---|---|
| filter | an element | a List of the elements where it returned true |
| map | an element | a List of the lambda's results, same length |
| fold(initial) | the accumulator and an element | one value, the final accumulator |
| groupBy | an element | a Map from each key to the matching elements |
| sortedBy | an element | a List ordered by the key the lambda returns |
| associate | an element | a Map built from the Pair the lambda returns |
Chains read top to bottom like a recipe: filter first to throw data away early, then transform, then summarise. Each step returns a new collection and never modifies the one it was given, so the original list is safe to reuse. fold deserves special attention because the initial value fixes the result type: fold(0.0) accumulates a Double, while fold(0) with Double amounts is a compile error. reduce has no initial value and therefore throws on an empty collection, where fold simply returns its initial value.
The cost question has a specific answer. A normal lambda is represented by a function object at run time, and every captured variable has to be stored in it. Marking the higher-order function inline tells the compiler to copy the function body and the lambda body into every call site, so no object is created and the lambda becomes a plain block of code. filter, map, fold, forEach and most standard collection functions are inline. The price is code size, which is why you add inline to small functions that take lambdas, not to large ones.
- Start with the source collection
- Each step takes a lambda rule
- Each step returns a new result
- The last step shapes the answer
Ask of every step: what goes in and what comes out? If you cannot say it in one sentence, split the lambda.
General pattern
fun <T> List<T>.name(rule: (T) -> Boolean): ResultType { ... }
collection
.filter { element -> condition }
.map { element -> newValue }
.fold(initial) { accumulator, element -> nextAccumulator }
inline fun name(block: () -> Unit) { ... }The first form is your own helper that takes a function type parameter. The second is a chain in which every step receives its lambda with its own parameter names. Add inline only to small functions whose lambda you want copied into the call site.
Worked example: answering four questions about orders
The program answers the lesson's problem. It mixes one helper of our own, countWhere, with the standard toolbox: filter, map, fold, groupBy, sortedByDescending and associateBy. Each question gets its own line, so you can tell what is being computed just by reading.
data class Order(val id: Int, val customer: String, val total: Double, val paid: Boolean)
fun <T> List<T>.countWhere(test: (T) -> Boolean): Int {
var count = 0
for (item in this) {
if (test(item)) count++
}
return count
}
fun main() {
val orders = listOf(
Order(1, "Ada", 120.0, true),
Order(2, "Linus", 35.5, false),
Order(3, "Ada", 60.0, true),
Order(4, "Grace", 210.0, true),
Order(5, "Linus", 80.0, true),
)
val paid = orders.filter { it.paid }
println("Paid ids: ${paid.map { it.id }}")
println("Unpaid count: ${orders.countWhere { !it.paid }}")
val revenue = paid.fold(0.0) { sum, order -> sum + order.total }
println("Revenue: $revenue")
val perCustomer = paid.groupBy { it.customer }
.mapValues { (_, list) -> list.sumOf { it.total } }
println("Per customer: $perCustomer")
val biggestFirst = paid.sortedByDescending { it.total }.map { it.customer }
println("Biggest first: $biggestFirst")
val byId = orders.associateBy { it.id }
println("Order 3 belongs to ${byId[3]?.customer}")
}Code breakdown
- Your own higher-order helper
fun <T> List<T>.countWhere(test: (T) -> Boolean): Int {The parameter test has the function type (T) -> Boolean, which makes countWhere higher-order. The body calls test(item) and counts the items for which it returns true. Because it is an extension on List<T>, you can write orders.countWhere { ... }.
- filter, then map
val paid = orders.filter { it.paid }filter returns a new List holding the four paid orders and leaves orders itself untouched. On the next line paid.map { it.id } swaps each Order for its id, giving [1, 3, 4, 5].
- fold with a Double start
val revenue = paid.fold(0.0) { sum, order -> sum + order.total }Starting from 0.0 makes the accumulator a Double, and for each order the lambda returns sum + order.total, which becomes the next sum. The result is 470.0. Starting from 0 would make the accumulator an Int and the code would not compile.
- groupBy, then mapValues
val perCustomer = paid.groupBy { it.customer }groupBy builds a Map that pairs each customer name with that customer's orders. mapValues then shrinks every list into a single number with sumOf { it.total }, producing {Ada=180.0, Grace=210.0, Linus=80.0}.
- Sorting by a key
val biggestFirst = paid.sortedByDescending { it.total }.map { it.customer }sortedByDescending orders by total, biggest first, and map keeps only the names. Ada appears twice because she has two orders with different amounts: [Grace, Ada, Linus, Ada].
- A lookup map
val byId = orders.associateBy { it.id }associateBy uses the id the lambda returns as the key and stores each Order under it. That lets byId[3] fetch order 3 directly instead of searching the whole list. A missing key gives null, which is why the safe call ?.customer is needed.
Paid ids: [1, 3, 4, 5]
Unpaid count: 1
Revenue: 470.0
Per customer: {Ada=180.0, Grace=210.0, Linus=80.0}
Biggest first: [Grace, Ada, Linus, Ada]
Order 3 belongs to Adainline: when a lambda costs nothing
Look at timed below. Because it is inline, the compiler pastes its body, lambda included, at every place it is called. Two consequences follow. No function object is created, and a return inside the lambda may return from the function that contains the call, which is why firstNegative can leave from inside forEach.
inline fun <T> timed(label: String, block: () -> T): T {
println("[$label] start")
val result = block()
println("[$label] done")
return result
}
fun firstNegative(numbers: List<Int>): Int? {
numbers.forEach { if (it < 0) return it }
return null
}
fun main() {
val total = timed("sum") { (1..100).sum() }
println("total = $total")
println(firstNegative(listOf(4, 7, -2, 9)))
println(firstNegative(listOf(1, 2)))
}The program prints [sum] start, [sum] done, total = 5050, then -2 and null. The restriction is symmetrical: an inline function cannot store its lambda parameter in a field, or hand it to non-inline code, unless the parameter is marked noinline. And crossinline forbids a non-local return when the lambda runs in another context, such as another lambda or an object. You rarely write those keywords; you only need to know why the compiler sometimes asks for them.
Sequences: lazy pipelines
A List pipeline is eager: filter finishes the whole list before map starts, and each step builds an intermediate list. A Sequence is lazy: asSequence turns the list into a pipeline where each element travels through every step before the next element starts, and nothing runs until a terminal operation such as first, toList or sum asks for a result. The output below shows both: the list version filters all six numbers, the sequence version stops after the second element because first() has what it needs, and the last line shows that a sequence without a terminal operation does nothing.
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6)
println("-- list (eager) --")
val fromList = numbers
.filter { println("filter $it"); it % 2 == 0 }
.map { println("map $it"); it * 10 }
.first()
println("result = $fromList")
println("-- sequence (lazy) --")
val fromSequence = numbers.asSequence()
.filter { println("filter $it"); it % 2 == 0 }
.map { println("map $it"); it * 10 }
.first()
println("result = $fromSequence")
numbers.asSequence().map { println("never printed $it"); it }
println("a sequence with no terminal operation did nothing")
}A Sequence is not always faster
On small lists the wrapper objects of a Sequence can cost more than they save. Reach for asSequence when a chain has several steps over a large collection, or when you stop early with first, take or find.
Scope functions: let, run, with, apply, also
Scope functions are small higher-order functions that run a lambda on an object. They differ in two questions only: inside the lambda do you refer to the object as this or as it, and do you want the object itself back at the end or the lambda's result.
| Function | Object is... / returns | Typical use |
|---|---|---|
| let | it, returns the lambda result | transform a nullable value: name?.let { ... } |
| run | this, returns the lambda result | compute a result from an object's members |
| with | this, returns the lambda result | call many members on one object: with(obj) { } |
| apply | this, returns the object itself | configure a freshly created object |
| also | it, returns the object itself | side effects such as logging inside a chain |
class Profile {
var name: String = ""
var age: Int = 0
}
fun main() {
val profile = Profile().apply {
name = "Ada"
age = 36
}
println("${profile.name}, ${profile.age}")
val nickname: String? = " linus "
val clean = nickname?.let { it.trim().replaceFirstChar { c -> c.uppercase() } }
println(clean)
val summary = profile.run { "$name is $age" }
println(summary)
val line = with(profile) { name.uppercase() + "/" + age }
println(line)
val logged = listOf(3, 1, 2)
.sorted()
.also { println("after sort: $it") }
.map { it * it }
println(logged)
}To choose, ask those two questions. When unsure, stick to let for nullable values, apply for configuring and also for logging; run and with are rarer. Avoid nesting scope functions inside each other, because the reader then has to track which object this and it refer to.
In real projects
Where higher-order functions show up in real projects
Most Kotlin code that touches data reads as a pipeline. A repository returns a list of database rows, a mapper turns them into display models with map, and a screen groups transactions by day with groupBy and totals each day with sumOf. Backend code does the same with request payloads: parse, filter out invalid items, transform, then group or summarise. UI toolkits such as Jetpack Compose are built from functions that take content lambdas, and Kotlin DSLs for builds and routing work the same way.
Two habits keep pipelines healthy. Put filter before map so that you transform less data, and use a Sequence when a chain has several steps over a large collection or stops early. When a lambda needs a comment to be understood, give it a name and pass it as a function reference.
- Reports and dashboards: groupBy and sumOf turn raw rows into totals per customer, day or category.
- Validation: filter or partition a list of inputs, then map the valid ones into domain objects.
- Lookups: associateBy builds a map once so that every later read is direct instead of a search through a list.
Common mistakes
Common mistakes with higher-order functions
Letting fold's initial value fix the wrong type
In orders.fold(0) { sum, order -> sum + order.total }, the 0 makes the accumulator an Int, so a Double cannot be added. The compiler reports argument type mismatch: actual type is 'Double', but 'Int' was expected. Use an initial value of the same kind as what you add up: 0.0 for Double, 0L for Long.
Calling reduce on a list that may be empty
emptyList<Int>().reduce { a, b -> a + b } throws UnsupportedOperationException: Empty collection can't be reduced., because there is no first element to start from. When the data may be empty, use fold, or reduceOrNull and handle the null.
Building a Sequence and never asking for a result
numbers.asSequence().map { println(it) } prints nothing, because there is no terminal operation. Using map for side effects is a poor habit anyway: on a List it creates a List<Unit> nobody wanted. Use forEach or onEach for side effects, and finish a sequence with a terminal operation such as toList or sum.
Best practices
Best practices
- Put filter before map so that unwanted data is dropped early.
- Match the initial value to the type you add up, and choose fold over reduce when the collection may be empty.
- Keep each lambda to a line or two and hand a named function to the pipeline when it grows.
- Do not nest scope functions, and choose one by what it returns: the object or the lambda result.
Mini challenge
Mini challenge: a word report
Write a small report for a list of words. First write your own higher-order extension, firstTwoWhere, which returns the first two elements that pass a test and stops as soon as it has two. Then group the words by their first letter and total the letters per group, use fold to join all the first letters into one String, and finally use a Sequence to find the first word of six or more letters in upper case.
- Declare firstTwoWhere as fun <T> List<T>.firstTwoWhere(test: (T) -> Boolean): List<T>
- Print the first two words longer than 4 letters
- Use groupBy and mapValues to print the total number of letters per first letter
- Use fold to join the first letters into one String, and asSequence() to print the first word of 6 or more letters in upper case
// TODO: return up to two elements for which test is true,
// and stop looping as soon as two have been found
fun <T> List<T>.firstTwoWhere(test: (T) -> Boolean): List<T> {
TODO()
}
fun main() {
val words = listOf(
"kotlin", "lambda", "map", "filter", "fold", "list", "lazy", "group",
)
// TODO: print the first two words longer than 4 letters, using firstTwoWhere
// TODO: group by first letter, print the total number of letters per letter
// TODO: use fold to join every first letter into one String
// TODO: use asSequence() to find the first word with 6+ letters, in upper case
}Expected: It prints [kotlin, lambda], then {k=6, l=14, m=3, f=10, g=5}, then klmffllg and finally KOTLIN.
Show hint
Inside firstTwoWhere, collect into a mutableListOf<T>() and break as soon as found.size == 2. For the totals chain words.groupBy { it.first() } into mapValues and use group.sumOf { it.length }. Write the Sequence version in the order filter, map, first.
Show solution
fun <T> List<T>.firstTwoWhere(test: (T) -> Boolean): List<T> {
val found = mutableListOf<T>()
for (item in this) {
if (test(item)) found.add(item)
if (found.size == 2) break
}
return found
}
fun main() {
val words = listOf(
"kotlin", "lambda", "map", "filter", "fold", "list", "lazy", "group",
)
println(words.firstTwoWhere { it.length > 4 })
val lettersPerInitial = words.groupBy { it.first() }
.mapValues { (_, group) -> group.sumOf { it.length } }
println(lettersPerInitial)
val initials = words.fold("") { text, word -> text + word.first() }
println(initials)
val shout = words.asSequence()
.filter { it.length >= 6 }
.map { it.uppercase() }
.first()
println(shout)
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A function that takes a function-typed parameter or returns a function is higher-order, and callers supply the rule with a trailing lambda.
- filter, map, fold, groupBy, sortedBy and associate handle the loop and accumulator for you, and the initial value of fold(initial) fixes the result type.
- inline copies the lambda into the call site, so no object is created and a return inside the lambda can leave the enclosing function.
- A Sequence runs each element through every step only when a terminal operation asks, and scope functions are chosen by this/it and by what they return.
Kotlin language guide — Kotlin