1. Why long chains are not always readable
When you first discover collection operations, it’s tempting to write everything “in one line”: normalization, filtering, grouping, sorting, and formatting. The code turns out compact, like vacuum packaging… but sometimes just as hard to unpack as that same vacuum packaging.
The problem is not that “chains are bad”. The problem is that a chain, like a toy snake, has a critical length: up to that point everything is cute; past that point you’re no longer sure where the head is and where the tail is. And if a week later someone asks you to “change the filtering rule just a bit”, you’ll stare at the code the way people stare at a microwave manual written in Japanese.
Let’s start with a simple example. Imagine that our training console project (a hypothetical “expense tracker”) stores operations the same way we agreed in our day plans: List<Pair<String, Int>>, where first is the category, and second is the amount.
fun main() {
val expenses = listOf(
" Food " to 120,
"FOOD" to 80,
" taxi" to 250,
"Books" to 90
)
val report = expenses
.map { it.first.trim().lowercase() to it.second }
.groupBy { it.first }
.mapValues { (_, items) -> items.fold(0) { acc, item -> acc + item.second } }
.entries
.map { it.key to it.value }
.sortedByDescending { it.second }
.take(3)
.joinToString(separator = "\n") { (cat, sum) -> "$cat: $sum" }
println(report)
}
Does it work? Yes. Is it readable? Well… “in its own way”. The key pain point is immediately visible: we mixed different levels of logic in one place. map and groupBy are about data, sortedByDescending and take are about presentation, joinToString is already about text. And inside mapValues there’s a fold hiding, which is itself an important aggregation stage.
Our goal is to make the pipeline read like a “story”: what we did first, what we did next, and what each step means.
2. Tools for decomposing a pipeline
When a chain starts to “grow”, there are two simplest and most powerful tools that save readability. And they save it without magic, without new libraries, and without the “functional zen” philosophy. Everything is as down-to-earth as it gets: you just add clear names and stopping points.
The first tool is intermediate val. These are “stops” in the pipeline: you take the result of an important step, put it into a variable with a meaningful name, and move on. The result is code where each val is like a chapter title in a book.
The second tool is step functions. If an operation repeats across multiple reports (for example, category normalization), or if a step is complex on its own, you extract it into a separate function with a clear “input → output” contract. This is especially good when you want main to stay short and read like a script.
What matters is that both tools solve the same problem, but from different sides. A val is convenient when the step is needed once and the local context matters right here. A function is convenient when you want to name and reuse the step, and also when you want to hide technical details. In Kotlin this fits naturally, because collection operations are just functions, often taking lambdas.
Intermediate val as stopping points
Intermediate val is the fastest way to make code clearer today without changing the project architecture. Mentally it’s similar to solving a math problem: instead of writing a half-page final formula right away, you first write “let A = …”, “let B = …”, and then everything becomes transparent.
Let’s refactor our report example into several val. Note: the logic is almost the same, but the reading is now linear.
fun main() {
val expenses = listOf(
" Food " to 120,
"FOOD" to 80,
" taxi" to 250,
"Books" to 90
)
val normalized = expenses.map { (cat, amount) ->
cat.trim().lowercase() to amount
}
val totalsByCategory = normalized
.groupBy { (cat, _) -> cat }
.mapValues { (_, items) -> items.fold(0) { acc, item -> acc + item.second } }
val top3 = totalsByCategory
.entries
.map { it.key to it.value }
.sortedByDescending { (_, sum) -> sum }
.take(3)
val report = top3.joinToString("\n") { (cat, sum) -> "$cat: $sum" }
println(report)
}
There’s an important effect here: each val is “type control”. You can see at a glance that after normalization you still have List<Pair<String, Int>>, after grouping and mapValues you have Map<String, Int>, and after sorting you got a list of pairs for output.
And one more detail: we applied sortedByDescending to a list of pairs, rather than trying to “sort a Map”. This is typical reality: Map is not about order, so before sorting you often switch to entries and turn them into a list. And if you ever feel tempted to say “let me just do sort()” — remember the difference: sort() changes a mutable collection in place, sorted()/sortedBy... return a new result.
A small pipeline diagram
To see the structure better, it’s sometimes useful to draw it as a chain of types:
List<Pair<String, Int>>
→ (normalize)
List<Pair<String, Int>>
→ (groupBy + sum)
Map<String, Int>
→ (entries → sort → take)
List<Pair<String, Int>>
→ (render)
String
When you keep this “type ladder” in mind, you get less confused about what you can sort, what you can group, and what is already “ready numbers”.
Step functions
Intermediate val works great while you’re writing one report. But as soon as you have several reports, you’ll start copying chunks: normalization repeats, “totals by category” repeats, rendering repeats. And that’s when the classic story begins: “I fixed it a bit in one place, and forgot in another”. The program is basically hinting that it’s time to extract repeatable steps into functions.
A step function is a small function with a single responsibility and a clear signature. You can read it like a phrase: normalizeExpenses, totalsByCategory, topCategories, renderLines. A good step function usually doesn’t print to the console and doesn’t read input — it just takes data and returns new data.
Let’s start with the most repeatable thing: category normalization. It’s a simple step, but it’s often needed in all reports.
fun normalizeCategory(raw: String): String =
raw.trim().lowercase()
Now apply it when normalizing the list of operations.
fun normalizeExpenses(expenses: List<Pair<String, Int>>): List<Pair<String, Int>> {
return expenses.map { (cat, amount) ->
normalizeCategory(cat) to amount
}
}
The map operation is the basic collection transformation operation: it builds a new collection from the results of transforming elements.
Now extract “totals by category” into a separate function. We’ll keep using groupBy, which gives Map<String, List<Pair<String, Int>>>, and then we’ll reduce each group into a sum. fold fits well here because it has a starting value and is safe on empty lists.
fun totalsByCategory(expenses: List<Pair<String, Int>>): Map<String, Int> {
val grouped = expenses.groupBy { (cat, _) -> cat }
return grouped.mapValues { (_, items) ->
items.fold(0) { acc, item -> acc + item.second }
}
}
And finally, the “prepare top-N” step. It should already work with aggregated data (Map<String, Int>), because top by “raw operations” means something completely different.
fun topCategories(totals: Map<String, Int>, n: Int): List<Pair<String, Int>> {
return totals.entries
.map { it.key to it.value }
.sortedByDescending { (_, sum) -> sum }
.take(n)
}
take(n) is that simple top-N trick: sort first, then take the first n.
Now rendering. Since it’s important to keep “calculation” separate from “text”, rendering is a separate function that returns a String. For assembling lines, it’s convenient to use StringBuilder.
import kotlin.text.StringBuilder
fun renderCategoryTotals(rows: List<Pair<String, Int>>): String {
val sb = StringBuilder()
for ((cat, sum) in rows) {
sb.append(cat).append(": ").append(sum).append('\n')
}
return sb.toString()
}
3. A readable script in main
When steps are separated, main starts to look like a script rather than a lab notebook full of chaotic formulas. And that’s an important psychological effect: you read the code top to bottom and understand the intent without having to squint at every lambda.
Let’s put it all together on a small dataset:
fun main() {
val rawExpenses = listOf(
" Food " to 120,
"FOOD" to 80,
" taxi" to 250,
"Books" to 90
)
val normalized = normalizeExpenses(rawExpenses)
val totals = totalsByCategory(normalized)
val top3 = topCategories(totals, n = 3)
val report = renderCategoryTotals(top3)
println(report)
}
One especially nice thing here: if you want to add another report (for example, “all categories alphabetically”), you won’t rewrite half the pipeline. You’ll just plug in a different data “presentation” function after totals. And if someone changes the normalization business rule (for example, “replace spaces with _” or “remove dots”), you update one function: normalizeCategory.
4. Contracts and step names
There’s a useful habit that quickly makes code more mature: looking not only at the function body, but also at its “external contract” — the name, parameters, and return type. A good step function is almost readable without its body: you can see what goes in, what comes out, and understand where it lives in the pipeline.
In Kotlin this is especially clear with fold: it takes a starting value and a combiner function, and returns the accumulated result. So even from the signature it’s clear: it’s an aggregation that turns many elements into one value.
Same idea for our steps:
- normalizeExpenses(expenses: List<Pair<String, Int>>): List<Pair<String, Int>> — the type doesn’t change; the data quality does.
- totalsByCategory(...): Map<String, Int> — a “turning point”: we move from a list of operations to aggregates.
- topCategories(...): List<Pair<String, Int>> — prepare a representation (sorting and limiting).
- renderCategoryTotals(...): String — turn data into text.
If at some point you catch yourself writing a function like fun doReportStuff(x: Any): Any, that’s not “generality”, it’s a signal that “we lost the structure”.
A simple rule works for variables and functions in pipelines: the name should explain the meaning of the step, not the internal mechanics. If you name a variable tmp2, you’re telling your future self: “I don’t know what this is, good luck”. If you name it totalsByCategory, you literally label what’s inside.
Below is a small table that’s useful to keep in mind when your hand reaches for data2:
| Bad (hides meaning) | Good (explains the step) |
|---|---|
|
|
|
|
|
|
And note: we don’t have to extract everything into functions. Sometimes one intermediate val is enough — and the chain becomes readable. Decomposition is not a religion of “everything into functions”, but common sense: “everything should have a name”.
5. Common mistakes
Mistake #1: extracting a “step” into a function that also prints.
At first you want to do something like: fun totalsByCategory(...) { ... println(...) }. But then you lose flexibility: you won’t be able to use the result in another report without extra output. It’s much more robust when steps return data and output is handled separately at the end.
Mistake #2: intermediate val that don’t clarify anything.
Sometimes a student honestly adds val a = ...; val b = ...; val c = ..., but the names are so abstract that it becomes even worse. Decomposition works only together with meaningful names: normalized, totals, top3, reportText.
Mistake #3: a “do-everything” function that does normalization, filtering, sorting, and rendering all at once.
Such a combine-all seems convenient while there’s only one. Then you add a second report — and realize there’s nothing to reuse. A pipeline lives well when each step has one result type and one responsibility: transform a list, get a map, get a top list, get a string.
Mistake #4: losing type control due to missing “stopping points”.
In a long chain it’s easy to stop understanding what you have right now: List? Map? Sequence? String? Intermediate val is often needed not “for beauty”, but so that at any moment you can say: “at this step I have Map<String, Int>”. groupBy is exactly the step where the type changes sharply to Map<K, List<V>>, and it’s convenient to capture that explicitly.
GO TO FULL VERSION