CodeGym /Courses /Kotlin SELF /Report set v0: total, byCategory, top, threshold in a uni...

Report set v0: total, byCategory, top, threshold in a unified style

Kotlin SELF
Level 26, Lesson 4
Available

1. Agree on the data: how reports receive expenses

When someone says “make a report,” a beginner often imagines a huge println that, by some miracle, calculates everything and draws it nicely. In practice, a report lives longer than inspiration: you come back to it, extend it, compare it with other reports. So the first grown-up decision is to agree on the shape of the input data and keep it stable at least at this stage of the course (no classes and no OOP yet).

In our practical console app about expenses (a conditional “mini-tracker”), we’ll assume that a single expense is a pair:

  • first: category (String)
  • second: amount (Int) in conditional “units”; the key point is: an integer

So the full list of expenses is List<Pair<String, Int>>.

Here is a small sample of the data we’ll work with next:

fun main() {
    val expenses: List<Pair<String, Int>> = listOf(
        " food " to 120,
        "FOOD" to 80,
        "taxi" to 250,
        "Books" to 90
    )

    println(expenses)
    // [( food , 120), (FOOD, 80), (taxi, 250), (Books, 90)]
}

Yes, the categories here are “dirty” (spaces, different casing). That’s not a mistake; it’s realistic. Users will always find a way to enter data so your program feels uncertain. We’ll just be smarter.

2. A shared step: category normalization

If you’ve ever grouped strings “as-is,” you’ve seen the magic in quotes: "Food" and " food " suddenly become different categories, and the report starts to look like the person eats in three parallel universes. To prevent that, normalization is a required shared step for all reports. And yes, normalization is not “pretty output”; it’s converting the data to a single internal representation before calculations.

Let’s make a tiny category-normalization function: trim() + lowercase(). It should be predictable, short, and the same everywhere.

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

fun main() {
    println(normalizeCategory("  FOOD ")) // food
    println(normalizeCategory("Books"))   // books
}

Now let’s apply normalization to all expenses. Note: we don’t modify the original list “in place”; we build a new one (this helps keep computations pure and reduces surprises).

fun normalizeExpenses(expenses: List<Pair<String, Int>>): List<Pair<String, Int>> {
    return expenses.map { (cat, amount) ->
        normalizeCategory(cat) to amount
    }
}

fun main() {
    val raw = listOf(" FOOD " to 10, "food" to 5)
    val normalized = normalizeExpenses(raw)

    println(normalized) // [(food, 10), (food, 5)]
}

Almost all our reports from here on will start with: “take expenses → normalize categories → compute.” That’s the “unified style.”

3. Report skeleton: computation separate from output

It’s very tempting to “make it pretty” right away: print lines during calculation, add emojis (but this is a Kotlin course, not Telegram stickers), align with spaces… and end up mixing computation and output so much that changing the format becomes more painful than getting up on Monday.

So we lock in the rule of the day:

  • calculation functions return numbers/structures (Int, Map, List<Pair<...>>)
  • render functions convert the result into a String (or print it, but returning a string is better)
  • main (or a command handler) decides what and when to show

Schematically it looks like this:

flowchart LR
    A[raw expenses] --> B[normalize]
    B --> C[calculate totals]
    C --> D[optional: filter threshold]
    D --> E[optional: sort + top-N]
    E --> F[render string]

In this lecture we’ll implement 4 reports (total, byCategory, top, threshold) so they feel like relatives, not random passers-by.

4. The total report: sum of all expenses

The total report seems the simplest: “add up all amounts.” But this is exactly where typical beginner mistakes start: an external counter, forgetting to reset it, an empty list “breaks the logic,” a random println somewhere in the middle, etc. Good news: Kotlin has fold, which is designed for neat accumulation.

Let’s write a function to compute the overall total. We sum second for each pair.

fun calcTotal(expenses: List<Pair<String, Int>>): Int {
    return expenses.fold(0) { acc, item ->
        acc + item.second
    }
}

fun main() {
    val expenses = listOf("food" to 10, "taxi" to 20)
    println(calcTotal(expenses)) // 30
}

Why fold(0) and not reduce? Because fold works even with an empty list: it starts with an initial value, and the result is predictable.

Now let’s create a renderer for total. Let it be a simple string:

fun renderTotal(total: Int): String {
    return "Total: $total"
}

fun main() {
    println(renderTotal(60)) // Total: 60
}

And immediately a small “assembly” example: normalization + total.

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

    val total = calcTotal(expenses)
    println(renderTotal(total)) // Total: 370
}

5. The byCategory report: totals by category

The “by category” report is the first moment when the data changes shape: we move from a list of individual operations to aggregated totals. And that’s normal: a report exists precisely to turn “raw events” into “understandable results.” The key is not to be afraid of changing types and to do it deliberately.

Our goal is to get a Map<String, Int>, where the key is the category and the value is the total for that category.

We’ll do it in two understandable steps: groupBy → mapValues + fold.

fun totalsByCategory(expenses: List<Pair<String, Int>>): Map<String, Int> {
    val grouped: Map<String, List<Pair<String, Int>>> =
        expenses.groupBy { it.first }

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

fun main() {
    val expenses = listOf("food" to 10, "food" to 5, "taxi" to 7)
    println(totalsByCategory(expenses)) // {food=15, taxi=7}
}

It’s useful to pause for a second and say it out loud: groupBy creates lists inside the map. That’s convenient for understanding, but sometimes heavy on memory. In earlier days you saw groupingBy { ... }.eachCount() and the general idea that you can group “without explicit lists.” Today we’re not chasing optimization; we’re chasing readability.

Now the render. An important nuance: with Map, you shouldn’t treat print order as a “report contract.” If you want deterministic output, you sort explicitly. This is directly related to ordering collections: sorting by key/value must be explicit, otherwise the order becomes “whatever happens.”

Let’s render it as a “table.” For simplicity: sort by category name.

fun renderByCategory(totals: Map<String, Int>): String {
    val rows: List<Pair<String, Int>> = totals.entries
        .map { it.key to it.value }
        .sortedBy { (cat, _) -> cat }

    val sb = StringBuilder()
    for ((cat, sum) in rows) {
        sb.append(cat).append(": ").append(sum).append('\n')
    }
    return sb.toString()
}

fun main() {
    val totals = mapOf("taxi" to 250, "food" to 200)
    print(renderByCategory(totals))
    // food: 200
    // taxi: 250
}

Notice: we return a string. Printing it or writing it to a file (someday later) is the caller’s decision.

6. threshold: the threshold as a separate step

A threshold (threshold) often appears in reports as “show only meaningful lines.” For example: “show categories where the total is >= 100.” The trap is simple: you can apply the threshold at the wrong time and get weird results. To avoid arguing with your future self, make the threshold a separate pure step that works with already aggregated data.

That is, threshold is filtering totals, not filtering individual operations. If you filter operations, the logic changes: you’ll start dropping small purchases even though the category total might be large.

Let’s make a function that takes a Map<String, Int> and returns a list of pairs that is convenient for further sorting/rendering:

fun applyThreshold(
    totals: Map<String, Int>,
    threshold: Int
): List<Pair<String, Int>> {
    return totals.entries
        .map { it.key to it.value }
        .filter { (_, sum) -> sum >= threshold }
}

fun main() {
    val totals = mapOf("taxi" to 250, "food" to 90, "books" to 110)
    println(applyThreshold(totals, threshold = 100))
    // [(taxi, 250), (books, 110)]
}

Right now it looks like “well yeah, a filter.” But the point is the architecture: you can plug this step into different reports in the same way, and the code reads like a constructor: “computed → filtered → sorted → output.”

7. The top report: top-N categories by total

Top-N is a typical “presentation” step: we’ve already computed everything, and now we decide what to show first. Sorting and take(n) are logical to do closer to the output: they don’t change the meaning of the data, they change how we present it to the user.

Let’s make a topCategories function that takes already aggregated totals. And we’ll connect the threshold as an option: filter by threshold first, then sort descending, then take(n).

fun topCategories(
    totals: Map<String, Int>,
    n: Int,
    threshold: Int
): List<Pair<String, Int>> {
    return totals.entries
        .map { it.key to it.value }
        .filter { (_, sum) -> sum >= threshold }
        .sortedByDescending { (_, sum) -> sum }
        .take(n)
}

fun main() {
    val totals = mapOf("taxi" to 250, "food" to 200, "books" to 90)
    println(topCategories(totals, n = 2, threshold = 100))
    // [(taxi, 250), (food, 200)]
}

Here the order is especially important. If you do take(n) first and apply the threshold afterward, you can “lose” lines: you took the first N before filtering, then threw some away, and the report suddenly shows fewer lines than it could. So threshold filtering must happen before take(n).

Now the top render. It’s almost the same as the byCategory render, but the order is already set (we sorted by amount). So the render just prints lines in the current order:

fun renderTop(items: List<Pair<String, Int>>): String {
    val sb = StringBuilder()
    for ((cat, sum) in items) {
        sb.append(cat).append(": ").append(sum).append('\n')
    }
    return sb.toString()
}

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

8. Assembling reports v0 into a unified style

Once you have more than two functions, your brain starts valuing rituals. Good style is not “pretty,” it’s “predictable”: you open the file a week later and immediately understand where to look for what. So let’s assemble everything into a small example, similar to how the code will live in our app (for now, still in one file).

Pay attention to the names of intermediate vals: they describe the pipeline steps.

fun main() {
    val rawExpenses = listOf(
        " food " to 120,
        "FOOD" to 80,
        "taxi" to 250,
        "Books" to 90,
        "books " to 30
    )

    val expenses = normalizeExpenses(rawExpenses)

    val total = calcTotal(expenses)
    println(renderTotal(total)) // Total: 570

    val totalsByCat = totalsByCategory(expenses)
    print(renderByCategory(totalsByCat))
    // books: 120
    // food: 200
    // taxi: 250

    val top = topCategories(totalsByCat, n = 2, threshold = 100)
    print(renderTop(top))
    // taxi: 250
    // food: 200
}

This already looks like a set of reports rather than one “divine println.” Yes, everything is still simple. But this is exactly the style that survives complexity: you add a report, and it fits into the same scheme.

Report contracts: what we accept and what we return

When you write many functions, it’s useful to keep the contracts in sight. This reduces the chance of “shoving the unshovable” and starting to pass a Map where a List is expected. Below is a compact table of our v0 functions.

Function Takes Returns Meaning
normalizeExpenses(...)
List<Pair<String, Int>>
List<Pair<String, Int>>
Bring categories to a unified form
calcTotal(...)
List<Pair<String, Int>>
Int
Total of all expenses
totalsByCategory(...)
List<Pair<String, Int>>
Map<String, Int>
Totals by category
applyThreshold(...)
Map<String, Int>
,
threshold
List<Pair<String, Int>>
Select categories by threshold
topCategories(...)
Map<String, Int>
,
n
,
threshold
List<Pair<String, Int>>
Top categories by total
render...(...)
numbers/structures
String
Prepare the report text

This table is not “documentation for the sake of documentation,” but a way not to get lost when there are more reports.

9. Common mistakes

Mistake No. 1: computing top from “raw” operations instead of aggregated totals.
If you take the original list of expenses and simply sort it by amount, you’ll get “the biggest individual spendings,” not “the most expensive categories.” Sometimes that’s even a useful report, but it’s a different report. For top by categories, do totalsByCategory first, and only then sort the totals.

Mistake No. 2: applying threshold after take(n) and being surprised why there are fewer rows than expected.
The logic “take top-2 first, then filter by threshold” can cause you to drop one line and end up with top-1 even though the data had candidates that would pass the threshold and could take the spot. The threshold is a candidate filter, while take(n) is the final “cutter,” so the threshold comes earlier.

Mistake No. 3: printing inside calculation functions.
As soon as you do println inside totalsByCategory or calcTotal, you break reusability. Today you print to the console; tomorrow you’ll want to build one big string; the day after, save it to a file. If calculation returns a value and output happens separately, you don’t corner yourself.

Mistake No. 4: expecting a Map to print itself in the needed order “by default.”
Even if “it happened to work like that right now,” it’s not a contract. A report should be deterministic: either sort by key, or by value, or explicitly document the order. In our examples, before output we turn entries into a list of pairs and sort it—this makes the result stable and readable.

Mistake No. 5: forgetting category normalization and getting “FOOD”, “food”, and “ food ” as three different worlds.
Classic: you group by a string, and the string is “dirty.” In reports this is especially painful, because a person looks at the totals and draws conclusions. So normalization is a shared step for all reports, and it’s best to keep it in a single function so the rules don’t drift apart.

Mistake No. 6: using reduce where the list can be empty and hitting an exception.
reduce requires at least one element; otherwise it has “nothing to start with.” For reports, an empty list is a normal situation (the user hasn’t added anything yet), so for sums and accumulations choose fold with a starting value. This makes behavior not only safe, but also logical: the sum of an empty set is zero, and nobody cries.

1
Task
Kotlin SELF, level 26, lesson 4
Locked
Receipt total
Receipt total
1
Task
Kotlin SELF, level 26, lesson 4
Locked
Total using fold
Total using fold
1
Task
Kotlin SELF, level 26, lesson 4
Locked
Category summary
Category summary
1
Task
Kotlin SELF, level 26, lesson 4
Locked
Report threshold
Report threshold
1
Survey/quiz
Reports and transformation pipelines, level 26, lesson 4
Unavailable
Reports and transformation pipelines
Reports and transformation pipelines
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION