Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 10 / Topic 8 of 8

Putting it together: a report pipeline

A kirana store's monthly spend report, using this whole part's toolkit: a Sequence for an early-exit scan, fold/groupBy for the numbers, and scope functions to assemble the result without throwaway variables.

var scanned = 0
val firstThreeLarge = TRANSACTIONS.asSequence()
    .onEach { scanned++ }
    .filter { it.amountInr > 2000.0 }
    .take(3)
    .toList()

val total = TRANSACTIONS.fold(0.0) { acc, t -> acc + t.amountInr }
val byCategory = TRANSACTIONS.groupBy { it.category }
    .mapValues { (_, list) -> list.sumOf { it.amountInr } }
    .toList()
    .sortedByDescending { (_, amount) -> amount }

val headline = byCategory.firstOrNull()?.let { (category, amount) ->
    "$category leads spend at ₹%.2f".format(amount)
} ?: "No transactions this month"

val report = StringBuilder().apply {
    appendLine("=== Monthly Spend Report ===")
    appendLine("Total spend: ₹%.2f".format(total))
    appendLine(headline)
    byCategory.forEach { (category, amount) -> appendLine("  $category: ₹%.2f".format(amount)) }
}.also { println("also: report built, ${it.lines().size - 1} lines") }
    .toString()
First 3 transactions over ₹2,000: [T2, T4, T5] (scanned 5 of 8)
also: report built, 8 lines
=== Monthly Spend Report ===
Total spend: ₹35710.00
Electronics leads spend at ₹15200.00
  Electronics: ₹15200.00
  Rent: ₹15000.00
  Entertainment: ₹2500.00
  Utilities: ₹1800.00
  Groceries: ₹1210.00
Average transaction: ₹4463.75

A few design choices worth noticing:

  • The sequence scan stopped at 5 transactions, not all 8, because take(3) was satisfied once the third transaction over ₹2,000 (T5) was found — the remaining 3 never needed to run.
  • firstOrNull()?.let { ... } is the pattern from section 4's let, now protecting against an empty byCategory instead of a null single value — the headline degrades to a plain sentence instead of throwing on an empty report.
  • apply builds the whole report on one StringBuilder and hands the same builder back, so .also { ... } (a log line) and .toString() can chain straight off it with no intermediate val.

Full program: examples/08_report_pipeline.kt.

Done here? The practice set for Part 10 — including the solutions — is on the part page.

Search the guide