Skip to content
Tutorials Center
My learning

Topics

Lesson 125 of 134 ยท Projects

Project: Inventory and Reports

Build an inventory report generator in Kotlin - parse CSV text safely, group and total with the collections API, sort with comparators, and print aligned tables, with every step runnable.

Most real programs spend their time on one job: take some data, group it, total it and print a report. An inventory is a friendly example. You have products with quantities and prices, and people want to know "what is running low?", "what is each category worth?" and "which items earn the most?". This project shows how much of that work the Kotlin collections API does for you when you use it well.

You will practice maps, grouping and aggregates, sorting with comparators, string formatting and text processing. It follows the bank project and is followed by the text adventure.

The data

Real systems read data from files or databases. Our runner has no persistent files, so the data is a CSV text inside the program: one product per line, with fields sku,name,category,quantity,price. The price is in cents, because we learned in the bank project not to use Double for money.

TEXT
sku,name,category,quantity,price
T-100,Claw hammer,Tools,14,1899
...

The program has four jobs: parse the text into objects, analyze them (group, total, rank), format the results as aligned tables, and drive it all from commands. We build them in that order.

Step 1: parsing without crashing

Input data is never perfect. A good parser keeps the good rows and reports the bad ones with line numbers, instead of stopping at the first problem. We model one parsed row as either a product or an error, using a sealed interface.

Kotlin Step 1 - parse CSV safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Some details here are worth a closer look:

  • val (sku, name, ...) = fields destructures a list. Lists support component1() to component5() (destructuring). We checked the size first, so the destructuring is safe.
  • toIntOrNull() ?: return Row.Bad(...) combines a safe conversion with an early return. The return has type Nothing, so it fits on the right side of the Elvis operator (null safety).
  • withIndex() pairs each line with its index, so error messages can use real line numbers. We add 1 because humans count from one, and header is line 1.
  • valueCents is a computed property, not a stored one, so it can never be out of date.
  • quantity * priceCents multiplies Int by Long, which Kotlin allows because the result type is Long (the Int operand widens in times overloads).

Step 2: grouping, totals and rankings

This is where the collections API shines. Each question below is one expression:

Question Function
Items per category groupBy
Value per category groupBy + sumOf, or groupingBy + fold
Out of stock / low stock filter
Most valuable items sortedByDescending + take
Cheapest and dearest minByOrNull, maxByOrNull
Split into two groups partition
Kotlin Step 2 - analyzing the inventory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

groupBy returns a Map whose keys appear in the order of the first occurrence, so the output order is deterministic (it uses a LinkedHashMap internally). mapValues keeps the keys and transforms the lists into totals. Destructuring partition gives the two halves directly.

Notice minByOrNull and maxByOrNull. They return null for an empty list. The versions without OrNull throw an exception. The following example fails on purpose to show that. Whether to prefer a nullable or an exception depends on whether "empty" can legitimately happen; for data coming from users or files, it can.

Kotlin An empty list has no maximum (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first line prints no products. The second one ends the program with NoSuchElementException and a stack trace that points to main.kt. The ?. and ?: combination in the first line is the fix: it returns a default when there is nothing to find.

Step 3: aligned tables

A report is read by people, so alignment matters. The idea is simple: first measure the widest value in each column, then pad each cell to that width. Text columns are left-aligned with padEnd; number columns are right-aligned with padStart. We write the helper as a function that takes a header and rows of strings and a list of alignments.

Kotlin Step 3 - a reusable table printer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The helper needs no knowledge of products: it is a pure function from strings to a string. That makes it reusable for every report in this project, and easy to test. buildString with appendLine builds the text without repeated string concatenation (strings).

length counts UTF-16 code units, not what you see on screen. A table with emoji or Chinese text will not align in a monospace font, because those characters are drawn wider or consist of two code units. For ASCII data, as here, it is exact.

Step 4: the report program

Now we combine the pieces. The program reads commands from stdin and prints the matching report:

  • summary totals per category,
  • low N items with quantity below N,
  • top N most valuable stock,
  • category NAME all items of a category,
  • problems lines that could not be parsed.
Kotlin Step 4 - the report generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Study how the program is organized:

  • Inventory receives a clean List<Product>. Parsing problems never reach it, so its code has no validation noise.
  • Every report returns a String instead of printing. The caller decides what to do with it: print, test or send over the network. Functions that return values are easier to test than functions that print.
  • The final when is used as the argument of println. Each branch is an expression producing the text.
  • category garden finds Garden because of equals(name, ignoreCase = true). User input rarely matches the data's capitalization.
  • Sorting by a Map.Entry uses destructuring in the lambda: { (_, items) -> ... }; the underscore marks the unused key.

Choosing the right collection function

Beginners often write loops with a mutable counter for tasks that have a named function. A short guide:

  • Total of something: sumOf { ... }. Count with a condition: count { ... }.
  • "Does any item match": any, "do all": all, "does none": none.
  • A map from a key to a single item: associateBy { it.sku }. A map from a key to a list: groupBy.
  • "Count per key": groupingBy { it.category }.eachCount().
  • Process big lists in several steps and you only need a few results: consider sequences, which do not build intermediate lists.

For an inventory of a few thousand products, plain lists are perfectly fast. Measure before you optimize.

Ideas to extend it

  1. Read the SKU from the user and implement restock T-101 20 and sell T-100 2, returning a sealed result like in the bank project.
  2. Add a reorder report: items with quantity < threshold grouped by category, with the quantity needed to reach the threshold.
  3. Add CSV quoting rules (fields with commas inside quotes). That quickly shows why libraries exist for CSV.
  4. Export the report as Markdown or JSON text (JSON text).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the parser return Row.Bad values instead of throwing an exception on the first bad line?

    Real input contains bad lines. Collecting problems as values lets the program continue and report every issue at once.
  2. 2. What does products.groupBy { it.category } return?

    groupBy builds a Map<K, List<V>>; keys appear in the order they were first seen.
  3. 3. What is the difference between maxBy and maxByOrNull on an empty list?

    The OrNull variants return null when there is no element, so you can handle the empty case with ?. and ?:.
  4. 4. In the table helper, why are number columns aligned with padStart?

    Right alignment puts units, tens and hundreds under each other, which makes columns of numbers readable.

Summary

  • Parse input into typed objects first; keep bad rows as values with line numbers instead of crashing.
  • groupBy, partition, sumOf, sortedByDescending, take, minByOrNull and maxByOrNull answer most report questions in one line each.
  • Use the OrNull variants (or provide defaults) when a collection might be empty.
  • Measure column widths, then use padEnd for text and padStart for numbers.
  • Make report functions return strings so they are reusable and testable.
  • Keep money in integer cents and format at the edge.

Next: Project: A Text Adventure Engine