The Analogy: The Grading Shed at a Wholesale Produce Market
Before dawn at the wholesale market, crates of fruit come off the lorries and into the grading shed, where three quite different jobs happen at once. At the first bench a grader picks up each apple and drops it into one of several bins according to a rule: Extra to the left bin, Class I to the middle, Class II to the right. When the crate is empty every apple sits in exactly one bin, and each bin holds all the apples that share a grade. Nothing was thrown away and nothing was totalled; the crate was simply partitioned, item by item, according to a rule applied to each apple in turn.
At the second bench a clerk keeps the supplier ledger. Every delivery arrives with a docket, and the clerk files each docket under the supplier's number, one slot per supplier, so that a query about supplier 12 goes straight to slot 12 and returns that supplier's docket. There is room for only one docket per number: if a second delivery comes in under a number already filed, the new docket goes on top and the old one is pulled and binned. The ledger answers "what is the current docket for this supplier," not "every docket this supplier ever sent."
At the far wall stands the weighbridge. Crates roll across it one at a time, and the operator keeps a running subtotal chalked on a board: he starts the board at zero, and as each crate crosses he adds its weight to the number already there and rubs out the old figure. By the time the last crate has crossed, the board shows the total weight of the whole delivery. The essential parts are the starting figure, which must be zero, and the single rule "new total equals old total plus this crate," applied crate after crate, carrying the sum forward the length of the shed.
The three benches are trustworthy only as far as their rules are. If the grader's rule has a fuzzy boundary, an apple lands in a bin where it does not belong and no later glance will catch it, because every bin looks full and plausible. If the clerk files two suppliers under one number, one supplier's docket vanishes without a trace. And if the weighbridge operator forgets to wipe the board to zero and starts from yesterday's leftover figure, every delivery reads heavy by the same hidden amount. The results look authoritative precisely because the work is mechanical; a wrong rule or a wrong starting figure hides inside a tidy answer.
Syntax or Core Structure
Kotlin gives each bench a function. groupBy partitions a collection into a Map of key to list, exactly like the grading bins. associateWith (and its siblings) builds a lookup keyed by a chosen value, like the supplier ledger. fold threads an accumulator through the collection from a starting seed, like the weighbridge.
fun main() {
val crates = listOf("apple", "pear", "apple", "plum", "pear", "apple")
val byInitial = crates.groupBy { it.first() }
val lengths = crates.associateWith { it.length }
val initials = crates.fold("") { acc, s -> acc + s.first() }
println(byInitial)
println(lengths)
println(initials)
}
Output:
{a=[apple, apple, apple], p=[pear, plum, pear]}
{apple=5, pear=4, plum=4}
apappa
groupBy { it.first() } drops each word into the bin named by its first letter: three words start with a and three with p, and the keys appear in first-encounter order. associateWith { it.length } builds a map from each distinct word to its length, so the three apple entries collapse to one key. fold starts with an empty string and appends each word's first letter in turn, spelling apappa -- one character per word, in order. Three benches, three shapes of answer from the same six crates.
Technical Depth: Which Bench For Which Job
The five functions side by side
| Function | Returns | Values kept per key | Which bench |
|---|---|---|---|
groupBy | Map<K, List<V>> | all, gathered in a list | the grading bins |
associateBy | Map<K, V> | one, last write wins | the supplier ledger |
associateWith | Map<V, R> | one, keyed by the element | ledger keyed by element |
fold | a single accumulated value | not applicable | the weighbridge, seeded |
reduce | a single value, same type | not applicable | weighbridge, no seed |
The distinction that trips people is groupBy against associateBy. Both take a key selector, but groupBy keeps every element that maps to a key, gathered in a list, while associateBy keeps only one element per key and the last one written wins. Choose by whether a key can legitimately have many members.
fold has a seed, reduce does not
fold takes an explicit starting value and can accumulate into a different type than the elements; reduce uses the first element as its seed and therefore throws on an empty collection.
fun main() {
val nums = listOf(2, 3, 4)
println(nums.fold(0) { acc, n -> acc + n })
println(nums.reduce { acc, n -> acc + n })
println(nums.fold(100) { acc, n -> acc + n })
println(emptyList<Int>().fold(0) { acc, n -> acc + n })
}
Output:
9
9
109
0
The first two lines agree at 9 because the seed for fold was 0, the identity for addition, and reduce started from the first element. The third line seeds with 100 and lands at 109, showing how the seed enters the total. The fourth line is the reason to prefer fold: it returns 0 on an empty list, whereas reduce on an empty list throws UnsupportedOperationException. Whenever a collection might be empty, fold with a correct seed is the safe choice.
associateBy keeps the last write
The supplier ledger has one slot per key, so a repeated key overwrites.
data class Supplier(val id: Int, val name: String)
fun main() {
val ds = listOf(Supplier(1, "acre"), Supplier(2, "brook"), Supplier(1, "combe"))
val byId = ds.associateBy { it.id }
println(byId)
println(byId[1])
println(byId.size)
}
Output:
{1=Supplier(id=1, name=combe), 2=Supplier(id=2, name=brook)}
Supplier(id=1, name=combe)
2
Two suppliers share id 1. associateBy files acre under key 1 first, then combe arrives under the same key and overwrites the value while the key keeps its original position. The map has two entries, and byId[1] is combe -- the last write. If you needed both suppliers under id 1 you wanted groupBy, not associateBy; the ledger only ever holds the current docket.
Named aggregates over manual folds
Many common totals have a dedicated function that is clearer than a hand-written fold, and each has a defined behaviour on an empty collection.
fun main() {
val prices = listOf(120, 80, 200, 50)
println(prices.sumOf { it })
println(prices.maxByOrNull { it })
println(prices.count { it > 100 })
println(emptyList<Int>().maxOrNull())
}
Output:
450
200
2
null
sumOf totals the four prices to 450 without a manual seed, maxByOrNull returns the largest element (200), and count with a predicate reports the two prices above 100. The last line shows the safety valve: maxOrNull on an empty list is null rather than an exception, the same reason fold beats reduce on empty input. Reach for these named aggregates first, and keep fold for accumulations the library does not already provide.
Real World Example: Totalling a Morning's Crates
The shed wants three answers before the market opens: the total weight per grade, the grand total across all grades, and a quick index from supplier to their latest crate. Each answer is one of the three benches.
data class Crate(val grade: String, val supplier: String, val kg: Int)
fun main() {
val crates = listOf(
Crate("I", "acre", 20),
Crate("II", "brook", 15),
Crate("I", "combe", 25),
Crate("II", "acre", 10),
Crate("I", "acre", 30)
)
val perGrade = crates.groupingBy { it.grade }
.fold(0) { acc, c -> acc + c.kg }
val correctTotal = crates.fold(0) { acc, c -> acc + c.kg }
val flawedTotal = crates.fold(crates.first().kg) { acc, c -> acc + c.kg }
val bySupplier = crates.associateBy { it.supplier }
println("per grade: " + perGrade)
println("correct total: " + correctTotal)
println("flawed total: " + flawedTotal)
println("suppliers indexed: " + bySupplier.size)
println("acre docket kg: " + bySupplier["acre"]?.kg)
}
Output:
per grade: {I=75, II=25}
correct total: 100
flawed total: 120
suppliers indexed: 3
acre docket kg: 30
The per-grade total uses groupingBy { it.grade } to open a bin per grade and fold(0) to run a seeded weighbridge inside each bin. Grade I gathers the crates of 20, 25 and 30 kilos for 75, grade II gathers 15 and 10 for 25, and the bins print in first-encounter order because groupingBy builds a LinkedHashMap. This is the pattern to reach for whenever you want one aggregate per group in a single pass.
The grand total is computed twice, and the two disagree. correctTotal seeds the fold with 0, the identity for addition, and lands on 100 -- the true sum of 20, 15, 25, 10 and 30. The supplier index uses associateBy { it.supplier }, which files one crate per supplier; acre sent three crates, so the first two are overwritten and bySupplier["acre"] is the last, the 30-kilo crate, which is why the final line prints 30.
The flawedTotal line is the defect, and it is the weighbridge that never got wiped to zero. It seeds the fold with crates.first().kg, the first crate's 20 kilos, and then adds every crate including that first one, so the 20 is counted twice and the total reads 120 -- heavy by exactly the seed. The rule "new total equals old total plus this crate" is correct; the starting figure is not. This is the design flaw to carry away: fold is only as right as its seed, and for a sum the seed must be 0, never the first element.
There is a second, quieter limitation in the same code worth naming. The bySupplier index is built with associateBy, so acre's 20-kilo and 10-kilo crates are silently dropped from the index; they remain correctly counted in perGrade, but anyone reading bySupplier to audit acre's deliveries would see only the last crate. If the goal were every crate per supplier, the code should have used groupBy, not associateBy -- the ledger holds one docket per number by design, and here that design quietly discards data.
Common Mistakes
- Seeding
foldwith the wrong starting value. For a sum the seed must be 0, for a product 1, for string building an empty string. Seeding a sum with the first element, as the flawed total above did, double-counts that element and skews the result by a constant.
- Reaching for
associateBywhen a key has many members.associateBykeeps one value per key and overwrites on collision, so earlier members vanish. When a key can legitimately map to several elements, usegroupBy, which gathers them all into a list.
- Calling
reduceon a possibly-empty collection.reduceuses the first element as its seed and throwsUnsupportedOperationExceptionon an empty collection. Usefoldwith a seed, orreduceOrNull, when the input might be empty.
- Confusing
groupBywithgroupingBy.groupByeagerly returns aMap<K, List<V>>;groupingByreturns a lazyGroupingmeant to be finished witheachCount,foldorreduceto aggregate per group in one pass. They are not interchangeable.
- Mixing up
associateBy,associateWithandassociate.associateBykeys by a selector and keeps the element as the value;associateWithkeeps the element as the key and computes the value;associatereturns a pair for full control. Picking the wrong one inverts your map.
- Assuming grouping output is sorted.
groupByandgroupingBypreserve first-encounter order, not sorted order. If you need alphabetical or numeric ordering, sort the entries explicitly after grouping.
- Writing a manual
foldwhere a named aggregate exists.sumOf,maxOf,minByOrNullandcountare clearer and less error-prone than a hand-rolled fold for the common totals. Reservefoldfor accumulations the library does not already name.
- Forgetting the empty-collection result of the max and min family.
maxByOrNullandminByOrNullreturnnullon an empty collection, and the non-OrNullvariants throw. Handle the empty case rather than dereferencing blindly.
- Letting duplicate keys silently overwrite in
associate. LikemapOf, the associate family keeps the last value on a key collision without warning. If two elements can share a key and you need both, decide the merge rule or group instead.
Best Practices
- Choose the bench by the shape of answer you need: many-per-key is
groupBy, one-per-key isassociateBy, and a single running value isfold.
- Always give
foldthe correct identity seed for its operation -- 0 for a sum, 1 for a product, an empty accumulator for building a collection or string.
- Prefer
foldwith a seed, orreduceOrNull, overreducewhenever a collection can be empty, so the empty case yields a value instead of an exception.
- Reach for a named aggregate --
sumOf,count,maxByOrNull-- before writing a manualfold, and keepfoldfor genuinely custom accumulations.
- Use
groupingBy { ... }.eachCount()orgroupingBy { ... }.fold(...)when you want a per-group aggregate in a single traversal rather than grouping and then mapping.
- Distinguish
associateBy,associateWithandassociateby which side is the key, and read the call back to confirm the map is oriented the way you meant.
- When keys can collide, decide the merge rule deliberately instead of relying on last-write-wins, or switch to
groupByto keep every member.
- Sort grouped output explicitly if the reader expects order; grouping guarantees only first-encounter order, which is rarely the order a report should show.
Practice Exercises
- Given a list of words, use
groupBy { it.first() }to bucket them by initial letter, then print each bucket. Confirm that every word appears in exactly one bucket and that no word is lost.
- Build a map from each distinct word to its length with
associateWith, then explain why a repeated word does not add a second entry. Contrast this with whatgroupBywould have produced.
- Compute the product of
listOf(2, 3, 4)withfold(1), then deliberately seed withfold(0)and explain the wrong answer. State the correct identity seed for a product.
- Fix the grading shed so the grand total seeds
foldwith 0, and changebySupplierto report every crate per supplier rather than only the last. Decide which function each requirement calls for.