CodeGym /Courses /Kotlin SELF /Report architecture as a pipeline

Report architecture as a pipeline

Kotlin SELF
Level 26, Lesson 0
Available

1. A report as a pipeline

When you hear the word “report”, a beginner’s brain often draws something like: “took a list → iterated over it → printed it”. This scheme works… right up until the first requirement like “also make top-3 categories”, “also filter only amounts ≥ X”, “also make it so that ‘Food’, ‘ food ’, and ‘FOOD’ are the same category”. At that moment, the code starts to resemble a tangle of cables under a desk: it sort of works, but it’s scary to touch.

So we need a different perspective: a report is a pipeline.

A pipeline is when we don’t do “everything at once”, but build a chain of steps:

vkhodnye dannye → preobrazovaniya → itogovye dannye → tekst otchyota

Important: a report almost always starts with “rough” data (the way the user entered categories, amounts, spaces, letter case) and ends with something “official”: numbers, structures, sorted lines.

Let’s lock in the core idea of the day:

A report is not “one magic chain”, but several simple steps arranged in the right order.

2. The order of pipeline steps

If you start writing a report “by inspiration”, it’s easy to mix up what should happen earlier and what should happen later. That’s why it helps to keep in mind a standard order that fits a huge number of data analysis tasks.

First, almost always, comes normalization. This means bringing input values to a “canonical” form: trim spaces, convert to lowercase, replace synonyms. Normalization matters because the report is built on key matches, and “food” and “FOOD” are different strings to a computer.

Then usually comes filtering. We drop what does not participate in the report: for example, negative amounts (if they’re not allowed), or expenses below a threshold, or “test” categories.

After that comes aggregation: we turn “many records” into “totals”. This is where fold, groupBy, groupingBy().eachCount(), and other things from previous days appear. groupBy() in Kotlin returns a Map, where the key is the result of the grouping function and the value is the list of elements in the group. And groupingBy() provides a way to compute results by groups “without explicit group lists” (for example, eachCount()).

Next comes sorting and selecting what we actually show (top-N via take(n)). This is closer to “presentation” than to “meaning”: we’re not changing facts, we’re deciding how to show them.

And only at the end comes building strings: turning the final data (numbers, pairs, maps) into nice text.

If it feels like “we’re making life more complicated” — yes, while writing the code it is a bit harder. But a week later you’ll thank yourself when you need to add a new report without breaking the old one.

3. Type control in a pipeline

Now an important point that often breaks beginners’ brains: each pipeline step changes the result type. And that’s normal.

A type change is not a mistake, but a hint: “we moved to the next level of processing”. If you keep track of types, you literally see the report’s architecture.

Let’s imagine that in our training console app (a hypothetical expense tracker) the data is still stored without classes, like:

// category to amount
val expenses: List<Pair<String, Int>>

Then a typical pipeline may look like this (in the table, types are intentionally “highlighted” — this is your compass):

Step What we do Input type Output type
1 Normalize categories
List<Pair<String, Int>>
List<Pair<String, Int>>
2 Filter (for example, amounts > 0)
List<Pair<String, Int>>
List<Pair<String, Int>>
3 Aggregate “sum by category”
List<Pair<String, Int>>
Map<String, Int>
4 Prepare lines for output (via sorting)
Map<String, Int>
List<Pair<String, Int>>
or directly
String
5 Render the report text
List<Pair<String, Int>>
String

Notice: in some places we stay in List, and in other places we sharply “shift over” into Map. That transition is an important boundary.

It is especially useful to remember groupBy(): after it you get a map of lists Map<K, List<V>>. This is often the very “turning point” where the coding style changes: instead of “processing elements” we start “processing groups”.

Mini data for examples

To keep the examples coherent, let’s agree on a small dataset. This is not the “final project architecture”, just a convenient format for the day: a pair (category, amount).

fun main() {
    val expenses = listOf(
        " Food " to 120,
        "FOOD" to 80,
        "taxi" to 250,
        " books" to 90
    )

    println(expenses)
    // [( Food , 120), (FOOD, 80), (taxi, 250), ( books, 90)]
}

Yes, categories here are “dirty” (spaces, different casing). That’s intentional: real life does not have to be pretty.

4. Normalization as an early step

Normalization is when we bring data to a single style so that identical entities match. In reports this most often applies to keys: categories, words, names, cities. If you normalize late (after grouping), you’ll get fragmented results: “food” separately, “FOOD” separately, “ Food ” separately. The report will look “plausible” but wrong — and that is the most dangerous kind of wrong.

Let’s do a simple normalization for a category: trim() + lowercase().

fun normalizeCategory(raw: String): String {
    return raw.trim().lowercase()
}

fun main() {
    val raw = listOf("  food ", "FOOD", " taxi")
    val normalized = raw.map(::normalizeCategory)

    println(normalized) // [food, food, taxi]
}

What matters here is that we apply normalization via map, which builds a new collection from transformation results. We don’t “fix the original”, we create a new, cleaner result.

Now let’s apply this to our expenses:

fun normalizeCategory(raw: String): String = raw.trim().lowercase()

fun main() {
    val expenses = listOf(" Food " to 120, "FOOD" to 80, "taxi" to 250)

    val normalizedExpenses = expenses.map { (cat, amount) ->
        normalizeCategory(cat) to amount
    }

    println(normalizedExpenses)
    // [(food, 120), (food, 80), (taxi, 250)]
}

Notice the type: it was List<Pair<String, Int>> and it stayed the same. This is an “early step” that does not change the data shape; it makes the data more suitable for analysis.

5. Grouping and changing the data shape

After normalization, grouping often comes next, because reports love phrases like “by categories”, “by users”, “by days of the week”.

In Kotlin, basic grouping is done with groupBy(): it returns a Map, where the key is what the grouping function returned, and the value is the list of group elements.

Let’s group expenses by category:

fun normalizeCategory(raw: String): String = raw.trim().lowercase()

fun main() {
    val expenses = listOf(" Food " to 120, "FOOD" to 80, "taxi" to 250)

    val normalized = expenses.map { (cat, amount) -> normalizeCategory(cat) to amount }
    val grouped = normalized.groupBy { it.first }

    println(grouped)
    // {food=[(food, 120), (food, 80)], taxi=[(taxi, 250)]}
}

This is where the “turning point” happened. The type was List<Pair<String, Int>>, and became:

Map<String, List<Pair<String, Int>>>

That is, a map of lists. And that makes sense: each category can have many records.

If you don’t need group lists

Sometimes a report doesn’t need the group elements; it only needs statistics. For example: “how many times did the category occur”. For this, groupingBy().eachCount() is often more convenient: it computes frequencies.

A mini example with words:

fun main() {
    val words = listOf("a", "bb", "ccc", "bb")
    val counts: Map<String, Int> = words.groupingBy { it }.eachCount()

    println(counts) // {a=1, bb=2, ccc=1}
}

Meaning: we immediately get a Map<String, Int>, i.e., a “final map”, without intermediate lists. This is especially nice when there is a lot of data.

For expenses, eachCount() will give “how many operations are in each category”, not sums. Sometimes that is useful as a separate report (“number of purchases by category”), but more often we still need sums — we’ll handle that in the next pipeline steps.

6. Aggregation and fold

Aggregation is the moment when we say: “enough details, give me the total”. The simplest aggregation is a sum.

In Kotlin, one of the key tools for this is fold(). It neatly walks through a collection and accumulates a result. Unlike reduce(), fold() takes an initial accumulator value, so it is safer for empty collections and better suited for beginners.

Let’s compute the total sum of expenses (this is the total report, but today we care specifically about the aggregation step):

fun main() {
    val amounts = listOf(10, 20, 30)
    val total = amounts.fold(0) { acc, x -> acc + x }

    println(total) // 60
}

If you ever wrote this using var sum = 0 and a loop — you already know fold, you just used to do it manually. Kotlin simply makes this pattern explicit and compact.

Now aggregation: “sum by categories”. We already have a Map<String, List<Pair<String, Int>>>. Now, inside each group, we need to fold the list into a number.

fun main() {
    val grouped = mapOf(
        "food" to listOf("food" to 120, "food" to 80),
        "taxi" to listOf("taxi" to 250)
    )

    val totalsByCategory: Map<String, Int> = grouped.mapValues { (_, items) ->
        items.fold(0) { acc, item -> acc + item.second }
    }

    println(totalsByCategory) // {food=200, taxi=250}
}

Here’s an important point about type control. After mapValues, we no longer have “operation lists”; we have “final numbers”. The pipeline moved from “details” to “result”.

And yes, mapValues is a map transformation (keys stay the same, values become new ones). This is exactly the “transform, don’t mutate” style that Kotlin nudges you toward via collection operations.

7. Sorting and preparing output

After aggregation, you want to show the result nicely: largest categories at the top, smaller ones below. This is not “changing the meaning”, it is presentation preparation.

A typical beginner problem: “How do I sort a Map?”. The answer is simple: most of the time you don’t sort the map “as-is”; you convert it to a list of elements (for example, pairs), sort the list, and print that.

Example: Map<String, Int> → List<Pair<String, Int>> → sort by sum descending.

fun main() {
    val totals = mapOf("taxi" to 250, "food" to 200, "books" to 90)

    val sorted = totals.entries
        .map { it.key to it.value }
        .sortedByDescending { (_, sum) -> sum }

    println(sorted)
    // [(taxi, 250), (food, 200), (books, 90)]
}

Again, track the types:

  • totals is a Map<String, Int>
  • totals.entries is a set of map elements (basically, a “list of map entries”)
  • .map { ... } turns that into a List<Pair<String, Int>>
  • .sortedByDescending returns a new sorted list (and does not touch the original data)

Next you can do top-N via take(n) — but the principle is already clear: sorting is done closer to output.

8. Rendering the report into a string

When you really want to see results quickly, your hand reaches for println() right inside aggregation. That gives immediate gratification, but it ruins the architecture: computation gets mixed with output. Later you’ll want to save the report to a string, print it in another format, or test it — and you’ll find that “everything prints itself”.

So the rule of the day: compute data first, then build text.

For building text, StringBuilder is convenient because it is meant for assembling strings without heavy concatenation in a loop. Kotlin also provides handy extensions for it (for example, .appendLine()).

Let’s make a simple renderer for a list of pairs (category, amount):

fun renderTotals(rows: List<Pair<String, Int>>): String {
    val sb = StringBuilder()
    for ((category, total) in rows) {
        sb.append(category)
        sb.append(": ")
        sb.append(total)
        sb.append('\n')
    }
    return sb.toString()
}

fun main() {
    val rows = listOf("taxi" to 250, "food" to 200)
    print(renderTotals(rows))
    // taxi: 250
    // food: 200
}

Notice: the function prints nothing. It returns a string. And printing is the job of main or the CLI layer.

It’s a small thing, but it’s exactly these small things that add up to “code you can maintain”.

9. Putting the whole pipeline together

Now let’s assemble a small complete pipeline example that makes an almost full report: normalization → aggregation → sorting → text.

Yes, we could do this as one chain of 8 calls. But today what matters is readable architecture: steps go in order, and we can visually see where each type is.

fun normalizeCategory(raw: String): String = raw.trim().lowercase()

fun main() {
    val expenses = listOf(
        " Food " to 120,
        "FOOD" to 80,
        "taxi" to 250,
        " books" to 90
    )

    val normalized = expenses.map { (cat, amount) ->
        normalizeCategory(cat) to amount
    }

    val grouped = normalized.groupBy { it.first }

    val totalsByCategory = grouped.mapValues { (_, items) ->
        items.fold(0) { acc, item -> acc + item.second }
    }

    val sortedRows = totalsByCategory.entries
        .map { it.key to it.value }
        .sortedByDescending { (_, sum) -> sum }

    val report = renderTotals(sortedRows)

    print(report)
    // taxi: 250
    // food: 200
    // books: 90
}

What’s important here (specifically from the “report architecture” point of view):

  • We don’t output in the middle, because the middle is still “data”, and it can be reused for other reports. This is especially useful in applications where you’ll want to show different reports off the same operations database.
  • We clearly see the type change at groupBy(), because groupBy() returns a Map. And then we clearly see that after fold inside mapValues, we end up with numbers (totals).
  • We sort before output so that line order is predictable. (If you rely on “however the map prints”, one day you may be surprised. Surprise is not the best format for financial reports.)

10. Common mistakes when designing a report pipeline

Mistake #1: mixing normalization and formatting.
When you do trim().lowercase() and immediately turn the result into a pretty string like “Category: …”, you tie data processing and presentation into a single knot. Then it turns out you need to use the same normalization for grouping, but without “Category:”. Much easier: normalize first “as data”, and only at the end format “as text”.

Mistake #2: not noticing the change in the result shape.
Beginners often keep thinking “I still have a list”, even though after groupBy() they already have a Map<String, List<...>>. This leads to strange attempts to call sortedBy “on a map” or to write a lambda that expects a list element but receives a Map.Entry. If you keep the type after each step in mind, half the confusion disappears on its own.

Mistake #3: grouping by a dirty key.
If you do groupBy { it.first } before trim/lowercase, you get a “correct” map… of incorrect keys. The report starts fragmenting, sums spread out, and then the user asks: “Why do I have two food categories?”. Because one is “food” and the other is “ Food ”. Normalization should almost always happen before grouping.

Mistake #4: trying to sort a Map “as-is”, then being surprised.
A map is not a list. In reports, sorting is most often done on a list of elements: take entries, turn them into pairs/strings, sort, then print. This is not a “workaround”; it’s the standard presentation-prep pattern.

Mistake #5: using reduce without thinking about empty data.
reduce has no initial value and can crash on an empty collection. fold is safer because it has an initial accumulator. In reports, empty data is a normal situation (for example, nothing has been added yet), so fold is usually more comfortable.

1
Task
Kotlin SELF, level 26, lesson 0
Locked
Clean categories
Clean categories
1
Task
Kotlin SELF, level 26, lesson 0
Locked
Cleaning up transactions
Cleaning up transactions
1
Task
Kotlin SELF, level 26, lesson 0
Locked
Operation groups
Operation groups
1
Task
Kotlin SELF, level 26, lesson 0
Locked
Category totals
Category totals
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION