1. Why reports need pure computations
Reports are a place in a program where a developer especially easily starts “to compute, and to print, and to tweak the data a little along the way.” It feels faster: here a println, there an in-place sort, there some counter in a var “that’s obvious anyway.” The problem is that a report is usually called many times and in different scenarios, and any hidden effects later turn into mysteries like “why is the total different today, even though the expenses are the same.”
In our console projects, a report is almost always a derived view of the data. It must not change the data itself, otherwise you start living in parallel realities: first “data as-is,” then “data that the report accidentally tweaked.” And guess which reality wins? Usually the one with bugs.
What a pure function is, and which effects get in the way
A pure function is a very down-to-earth idea: if you give it the same input data, it should return the same result. And at the same time it must not “do something else” silently: print to the console, change global variables, rewrite the input list, depend on randomness, or depend on the current time.
With Kotlin this is also convenient because the language nudges you toward careful work with collections: there are read-only interfaces (List, Map) and there are mutable variants (MutableList, MutableMap). A read-only collection prevents you from “accidentally” changing its contents, which lowers the chance of breaking data for no good reason.
Printing and input inside a calculation
Printing (println) is the trickiest side effect because it looks harmless: “I’m just going to peek at an intermediate result.” But once println ends up inside a report function, the function stops being “compute and return,” and becomes “compute and make noise along the way.” Later you call the report from somewhere else—and suddenly the console is flooded with messages you already forgot where they came from.
A reasonable boundary is this: the calculation function returns data (a number, a list of pairs, a map of totals), and printing happens outside, in main or in the CLI layer. Then you can test the report “in your head”: input → output, without distractions.
Mutating external state and why var looks suspicious here
The second class of effects is changing something “outside”: an external var, a global variable, a shared application-state collection. In reports this is especially dangerous because a report is usually called as “show the current state,” not “change the state.” If a report changes state, it becomes a command—even though conceptually it’s a query.
var is not evil by itself. But if you see in a report an external counter like var total = 0 that lives somewhere “outside” and accumulates values between calls, that is almost guaranteed to become a future puzzle. “Why does the second print of the report show double the sum?”—because var remembers its past life.
2. The effects boundary: calculation, render, print
To keep reports readable and predictable, we introduce a simple separation: first we compute the data, then we turn it into nice text. This is not “architecture for architecture’s sake,” but a practical way to save your nerves: if the numbers are wrong, you fix the calculation; if the text is ugly, you fix the render. And these tasks don’t interfere with each other.
It’s handy to think about the boundary like this: “everything that returns a String is presentation; everything that returns an Int, List<...>, Map<...> is computation.” Yes, there are exceptions, but for our level and for a console app this rule almost always improves the code.
A small diagram (in our expense tracker):
flowchart LR
A["Expense list
List of Pair(String, Int)"] --> B["Report calculation
(pure functions)"]
B --> C["Final data
Int / Map / List of Pair"]
C --> D["Render to string
(StringBuilder locally)"]
D --> E["println(...) in CLI"]
The idea of the diagram is simple: printing happens only at the very end, at the program boundary. Everything before it we try to do without side effects.
Allowed local mutation: StringBuilder and local MutableMap
An important clarification: “minimum side effects” does not mean “no var ever.” It means: don’t mutate external state and input data, and if mutation is needed, do it locally, under control, and return the result outward.
A classic example is StringBuilder. It is mutated (pieces of text are appended), but this happens inside the render function, and the function returns the final string to the outside. This is a good compromise: efficient and readable.
Another example is a local MutableMap inside an aggregation function. If you create a MutableMap inside a function and fill it without touching external variables and without returning the mutable reference “for further adventures,” that is usually acceptable. The idea is the same: local mutation for a result you return as a Map.
3. fold as a “pure counter” instead of external var
When a beginner wants to compute a sum, they almost always write a counter and a loop. That’s fine—we used to do it too. But in reports it’s more convenient to express accumulation via fold: then accumulation happens “inside the expression,” not through external mutation. Technically fold also has an accumulator, but it’s local and doesn’t leak outward. As a result, your code is easier to read and harder to break by accident.
Let’s compare two approaches.
The variant with an external var:
fun calcTotalBad(expenses: List<Pair<String, Int>>): Int {
var total = 0
for (e in expenses) {
total += e.second
}
return total
}
It works. But if you start printing “for convenience” inside the loop, or move total somewhere outside, you’ll quickly end up in a world of unexpected effects.
The variant via fold:
fun calcTotal(expenses: List<Pair<String, Int>>): Int =
expenses.fold(0) { acc, item -> acc + item.second }
Here it reads literally: “fold the list into a single number, starting from zero.” And importantly, this function cannot “accidentally” keep state between calls—there’s nowhere for it to live.
Mini-check:
fun main() {
val expenses = listOf("food" to 10, "taxi" to 20)
println(calcTotal(expenses)) // 30
println(calcTotal(expenses)) // 30
}
Called twice—got the same result twice. And the report did not “get tired” between calls.
4. Do not mutate input data
The “input mutation” problem in reports often looks like this: you have a list of expenses in the application state (usually a MutableList), you pass it into a report, and the report decides “for convenience” to change something in it. For example, delete invalid entries, sort it in place, normalize categories directly in the source list. Then the user goes back to the list and sees that the data changed—even though they did nothing; they only requested a report.
To prevent this, follow two rules.
Rule one: accept read-only types in calculation functions—List, Map, not MutableList, MutableMap. Even if inside your app you store a MutableList, you expose it (to the report) as a List. This doesn’t make the collection “magically immutable,” but it greatly reduces the chance you’ll start mutating it by accident, because the compiler simply won’t allow it.
Rule two: if you really need to “change data for the calculation,” perform a transformation that returns a new result (map, filter, sorted, etc.), rather than rewriting the input list. Kotlin collection transformations build a new collection by default instead of mutating the original, which is exactly what we want for reports.
A simple example of normalization without mutating the input:
fun normalizeCategory(raw: String): String =
raw.trim().lowercase()
fun normalizeExpenses(expenses: List<Pair<String, Int>>): List<Pair<String, Int>> =
expenses.map { (cat, amount) -> normalizeCategory(cat) to amount }
We don’t change anything “inside” expenses; we create a new list. The old one stays as it was.
5. Pure reports in a mini expense tracker
Now let’s put this into practice: imagine we already have a console expense tracker that stores operations as pairs (category, amount). We want to write reports so they don’t print inside themselves, don’t modify input data, and don’t depend on external variables. At the same time, reports should be easy to compose: one computes numbers, another produces text, a third prints.
We’ll develop the same style: “pure computations → pure render → effect (println) in main.” This will help us keep building a set of reports without turning main into a dumping ground of logic.
Data shape and normalization
Let’s start by fixing the basics: an expense is a Pair<String, Int>, where first is the category and second is the amount. The category may come in “dirty” (spaces, different case), so we normalize it ahead of time. It’s convenient to make normalization a separate function because it repeats in every report.
fun normalizeCategory(raw: String): String =
raw.trim().lowercase()
fun normalizeExpenses(expenses: List<Pair<String, Int>>): List<Pair<String, Int>> =
expenses.map { (cat, amount) -> normalizeCategory(cat) to amount }
Let’s test on a mini set:
fun main() {
val raw = listOf(" Food " to 120, "FOOD" to 80, "taxi" to 250)
val normalized = normalizeExpenses(raw)
println(normalized) // [(food, 120), (food, 80), (taxi, 250)]
}
An important point: raw did not change; we created a new list. That is “no input mutation.”
Pure calculation functions: total and totalsByCategory
Now let’s write pure calculation functions. We’ll start with the total sum. We already discussed fold: it’s a perfect fit because it expresses “accumulating a result” without external counters.
fun calcTotal(expenses: List<Pair<String, Int>>): Int =
expenses.fold(0) { acc, item -> acc + item.second }
Check:
fun main() {
val expenses = listOf("food" to 10, "taxi" to 20, "books" to 5)
println(calcTotal(expenses)) // 35
}
Now totals by category. We have two readable paths, both without mutating the input.
The first path: groupBy + mapValues. groupBy turns a list into a Map<K, List<V>>, where the key is the category and the value is a list of entries for that category. This is the “turning point” of the pipeline where the data shape changes drastically.
fun totalsByCategory(expenses: List<Pair<String, Int>>): Map<String, Int> {
val grouped = expenses.groupBy { it.first } // Map<String, List<Pair<String, Int>>>
return grouped.mapValues { (_, items) ->
items.fold(0) { acc, item -> acc + item.second }
}
}
Check:
fun main() {
val expenses = listOf("food" to 10, "food" to 5, "taxi" to 7)
println(totalsByCategory(expenses)) // {food=15, taxi=7}
}
mapValues is a standard map transformation that builds a new map without changing the original. We got the final structure Map<String, Int>, and from there the report can work with numbers rather than the original entries.
The second path (sometimes more convenient when you want one pass): carefully fold the list into a map via fold, using a local MutableMap. This is local mutation, but it is completely hidden inside the function and does not touch the input list. In the end we return a Map as the “final data.”
fun totalsByCategoryFold(expenses: List<Pair<String, Int>>): Map<String, Int> =
expenses.fold(mutableMapOf()) { acc, (cat, amount) ->
acc[cat] = (acc[cat] ?: 0) + amount
acc
}
Check:
fun main() {
val expenses = listOf("food" to 10, "food" to 5, "taxi" to 7)
println(totalsByCategoryFold(expenses)) // {food=15, taxi=7}
}
Both variants are correct. In teaching examples, the first one (via groupBy) is often easier to read because it literally shows the steps: “grouped → summed within each group.”
Pure rendering: turn final data into a string
Now let’s make a function that doesn’t compute, but formats nicely. Its job is to take already computed strings/numbers and return a String. Local mutation of a StringBuilder is allowed here because it is limited to one function and produces a predictable result.
fun renderTotals(rows: List<Pair<String, Int>>): String {
val sb = StringBuilder()
for ((category, sum) in rows) {
sb.append(category).append(": ").append(sum).append('\n')
}
return sb.toString()
}
Let’s test:
fun main() {
val rows = listOf("taxi" to 250, "food" to 200)
print(renderTotals(rows))
// taxi: 250
// food: 200
}
Notice: renderTotals does not print anything by itself. It returns a string, and printing is a decision of the calling code. That is the clean effects boundary.
6. Common mistakes in “pure” reports
Mistake #1: the report “computes” via println.
A style is often seen where you “compute and immediately print,” and sometimes also print intermediate values “for debugging.” At the time of writing it feels convenient, but later the report is impossible to reuse: you’ll want to display it in another format or combine it with another report, but it already makes noise in the console. The cure is simple: the calculation returns data, the render returns a string, printing lives outside.
Mistake #2: a report function accepts a MutableList and changes it “for convenience.”
This is especially nasty because conceptually a report is “view,” not “modify.” If inside a report you delete elements, fix categories, or change order, then after calling the report the application state is already different. Usually this shows up as a “flaky” bug: you call the report once—everything is ok; you call it again—things get weird. Accept a List and return a new result rather than modifying the input.
Mistake #3: an external counter in a var that lives longer than one call.
Sometimes “for speed” or “for simplicity” the sum is stored in an external variable and the report adds to it. After a couple of calls you get accumulation “for all time,” although you wanted “for the current data.” fold solves this almost always: it expresses accumulation locally and prevents you from accidentally keeping the past between calls.
Mistake #4: mixing normalization and formatting in one place.
When inside rendering you suddenly start doing trim().lowercase() and also replace spaces, reports become inconsistent: somewhere the category is normalized, somewhere it isn’t. As a result, one report will show Food, another food, and a third will show food . It’s better to agree on a rule: normalization is an early step shared by all reports and returns “clean data,” while formatting is the final step and works with normalized input.
Mistake #5: returning “almost-ready text” too early and losing the ability to post-process.
If you turn data into strings too early, it becomes inconvenient to sort, filter by a threshold, take top-N, and so on: you have to parse it back or build extra structures. A good habit is to keep data as numbers and pairs until the very end, and only in the last step produce a String. Then the report stays flexible and is easy to extend with the next pipeline steps.
GO TO FULL VERSION