Thuta Learning
Kotlin
AdvancedProgrammingBeginner

Mini Project

KotlinLesson 2345 min

What you'll walk away with

  • Split a program into slices: model, parsing, classification, summary and report
  • Turn untrusted text lines into typed values with Result and a sealed interface
  • Summarise data with filter, groupBy, mapValues and sumOf instead of loops
  • Verify a program with scripted data and check() assertions, without stdin

Explain it simply

The mini project in plain language

In this mini project you build a small enrollment report: a handful of course signup lines go in, and a readable report with revenue per course, unpaid balances and rejected lines comes out. The lines are written into the program as a list, so it runs the same way every time, with no keyboard input and no files. Everything in it comes from earlier lessons: data classes, lists, functions, lambdas, extension functions, Result and a sealed interface.

Think of a small shop's end-of-day routine. Sales slips arrive, and some are smudged or incomplete. You set the unreadable ones aside with a note, add up the good ones by product, and write a one-page summary for the owner. The program does the same three jobs: sort the slips, total the good ones, and report what was set aside.

Problem → Why → Solution

The problem: everything mixed together in main

The simplest way to write this is one long main function: split each line, ignore errors, add numbers in mutable variables and print as you go. It works on the happy path. But the moment a line is malformed, such as a missing field or a course that does not exist, the program either crashes in the middle of the report or quietly skips the line and gives a total that is wrong without anyone noticing.

A second problem is testing. Because parsing, calculation and printing are tangled together, the only way to check a rule is to read the printed output by eye. Change one rule and you cannot tell what else moved.

all-in-main.kt
fun main() {
    val lines = listOf("Mya, Kotlin Basics, true", "broken line")
    var total = 0
    for (line in lines) {
        val parts = line.split(",")
        total += parts[1].trim().length // IndexOutOfBoundsException on "broken line"
        println("processed $line")
    }
    println("total = $total")
}

Slicing the program fixes both problems

Separating the program into small slices fixes both problems. A parsing slice that returns a Result forces every line to be accepted or rejected with a reason, a summary slice that only receives clean typed data cannot crash on text, and a report slice only formats. Each slice can be checked on its own, and the check() calls at the end of main act as a tiny test: if a line goes missing, the program stops instead of printing a believable but wrong report.

Core concept: model, parse, classify, summarise, report

The project follows a pattern that scales from this exercise to real services: model, parse, classify, summarise, report. Each slice does one job and hands a typed value to the next. The model slice defines Level (an enum), Course, Enrollment and Line, a sealed interface with Accepted and Rejected. Nothing in it knows about text formats or printing.

The parse slice owns everything unsafe. parseEnrollment takes one raw line and returns Result<Enrollment>. Inside runCatching, require checks that there are three fields and that the student name is not empty, error reports an unknown course, and a when accepts only true or false, so 'maybe' fails instead of quietly becoming false (the standard library's toBooleanStrict does the same job). Every failure carries a message explaining the problem, and that message is exactly what the report later shows.

The classify slice converts the Result into the sealed Line type with fold. From this point nobody deals with exceptions: a line is either Accepted with an Enrollment or Rejected with the original text and a reason. filterIsInstance picks one kind out of the list and returns correctly typed elements, so accepted becomes a List<Enrollment> with no casts.

The summary slice is pure data processing with the toolbox from lesson 20: filter keeps paid enrollments, groupBy collects them by course title, mapValues and sumOf turn each group into revenue, and maxByOrNull finds the most active student. Because it works on typed values, it contains no string parsing and cannot throw on bad text. The report slice only formats: padEnd lines up the columns, and the extension function Int.asMmk() handles the money format in one place. Finally, check(accepted.size + rejected.size == script.size) states an invariant: no input line may vanish. If a future change breaks it, the program fails loudly instead of printing a believable but wrong report.

SliceInput and outputTools from the course
Modelno input; defines the typesdata class, enum class, sealed interface
ParseString -> Result<Enrollment>runCatching, require, error, when
ClassifyResult -> Linefold, sealed interface
SummaryList<Enrollment> -> numbersfilter, groupBy, mapValues, sumOf, maxByOrNull
Reportnumbers -> textextension function, padEnd, string templates, check
A factory line with checkpoints
  1. Raw lines enter the program
  2. Parse: accept or reject each line
  3. Summarise only the accepted data
  4. Report, then check nothing was lost

If a number in the report looks wrong, test the slices from the left: the parse first, then the classify, then the summary.

General pattern

kotlin
data class Model(val field: Type)

sealed interface Line {
    data class Accepted(val item: Model) : Line
    data class Rejected(val raw: String, val reason: String) : Line
}

fun parse(raw: String): Result<Model> = runCatching { ... }

fun classify(raw: String): Line =
    parse(raw).fold({ Line.Accepted(it) }, { Line.Rejected(raw, "...") })

Declare the model first, let parse capture everything unsafe in a Result, and let classify turn that Result into Accepted or Rejected. The summary and report slices then see typed values only.

Worked example: an enrollment report from scripted lines

The script has eight lines, and three of them are deliberately bad: an invalid paid value, an unknown course and a line with missing fields. The program must show those with their reasons instead of crashing. From the other five lines it computes revenue, unpaid balances and the most active student. Work out the total revenue in your head before you run it.

enrollment-report.kt
enum class Level { BEGINNER, INTERMEDIATE, ADVANCED }

data class Course(val title: String, val price: Int, val level: Level)

data class Enrollment(val student: String, val course: Course, val paid: Boolean)

sealed interface Line {
    data class Accepted(val enrollment: Enrollment) : Line
    data class Rejected(val raw: String, val reason: String) : Line
}

val catalog = listOf(
    Course("Kotlin Basics", 30000, Level.BEGINNER),
    Course("Android UI", 45000, Level.INTERMEDIATE),
    Course("Backend API", 50000, Level.ADVANCED),
)

val script = listOf(
    "Mya, Kotlin Basics, true",
    "Zin, Backend API, true",
    "Kyaw, Android UI, false",
    "Mya, Backend API, true",
    "Su, Kotlin Basics, maybe",
    "Hla, Rust Basics, true",
    "broken line",
    "Aye, Kotlin Basics, true",
)

fun Int.asMmk(): String = "$this MMK"

fun parseEnrollment(raw: String): Result<Enrollment> = runCatching {
    val parts = raw.split(",").map { it.trim() }
    require(parts.size == 3) { "expected 3 fields but found ${parts.size}" }
    val (student, title, paid) = parts
    require(student.isNotEmpty()) { "student name is empty" }
    val course = catalog.firstOrNull { it.title == title }
        ?: error("unknown course '$title'")
    val isPaid = when (paid) {
        "true" -> true
        "false" -> false
        else -> error("paid must be true or false, got '$paid'")
    }
    Enrollment(student, course, isPaid)
}

fun classify(raw: String): Line = parseEnrollment(raw).fold(
    onSuccess = { Line.Accepted(it) },
    onFailure = { Line.Rejected(raw, it.message ?: "unknown error") },
)

fun main() {
    val lines = script.map(::classify)
    val accepted = lines.filterIsInstance<Line.Accepted>().map { it.enrollment }
    val rejected = lines.filterIsInstance<Line.Rejected>()

    println("== Enrollment report ==")
    val counts = "accepted: ${accepted.size}, rejected: ${rejected.size}"
    println("Lines: ${lines.size}, $counts")

    println("-- Revenue (paid only) --")
    val revenue = accepted.filter { it.paid }
        .groupBy { it.course.title }
        .mapValues { (_, list) -> list.sumOf { it.course.price } }
    for (course in catalog) {
        println("${course.title.padEnd(14)} ${(revenue[course.title] ?: 0).asMmk()}")
    }
    println("Total: ${revenue.values.sum().asMmk()}")

    println("-- Unpaid --")
    for (e in accepted.filterNot { it.paid }) {
        println("${e.student} still owes ${e.course.price.asMmk()} for ${e.course.title}")
    }

    println("-- Rejected --")
    for (line in rejected) {
        println("'${line.raw}' -> ${line.reason}")
    }

    val perStudent = accepted.groupBy { it.student }.mapValues { (_, list) -> list.size }
    val busiest = perStudent.maxByOrNull { it.value }
    println("Most active: ${busiest?.key} with ${busiest?.value} courses")

    check(accepted.size + rejected.size == script.size) { "a line was lost" }
}

Code breakdown

  1. The modeldata class Enrollment(val student: String, val course: Course, val paid: Boolean)

    Enrollment stores the student name, the Course itself rather than just its name, and the paid flag. Holding the Course directly means later code can read it.course.price with no second lookup.

  2. Fail with a reason?: error("unknown course '$title'")

    firstOrNull gives null when nothing matches, and ?: error(...) throws IllegalStateException for that null. Because error has the type Nothing, it fits inside the expression. runCatching captures the exception, so the message unknown course 'Rust Basics' reaches the report.

  3. Strict inputelse -> error("paid must be true or false, got '$paid'")

    The when accepts only true and false and rejects everything else. That is why 'maybe' shows up as a rejected line instead of silently landing in the report as unpaid, a rule that protects the money figures from quiet errors.

  4. Result to sealed typefun classify(raw: String): Line = parseEnrollment(raw).fold(

    fold builds Accepted on success and, on failure, a Rejected holding the original text and the message. The return type Line is the common supertype of both, which lets Kotlin infer the type of fold's result. After this point no exception remains.

  5. Typed filteringval accepted = lines.filterIsInstance<Line.Accepted>().map { it.enrollment }

    filterIsInstance keeps only the Accepted lines and narrows the element type to Line.Accepted, so map { it.enrollment } needs no cast. The result is a List<Enrollment>.

  6. Group, then total.groupBy { it.course.title }

    Only paid enrollments are filtered in before grouping by course title, so Kyaw's Android UI is missing from the revenue because it is unpaid. mapValues and sumOf turn each group into a price total. Looping over the catalog therefore shows Android UI at 0 MMK.

  7. A self-checkcheck(accepted.size + rejected.size == script.size) { "a line was lost" }

    check states the invariant that every line is either Accepted or Rejected. It holds, so nothing visible happens, but if a later change makes a line fall through, the program stops with an IllegalStateException carrying that message.

You should see
== Enrollment report ==
Lines: 8, accepted: 5, rejected: 3
-- Revenue (paid only) --
Kotlin Basics  60000 MMK
Android UI     0 MMK
Backend API    100000 MMK
Total: 160000 MMK
-- Unpaid --
Kyaw still owes 45000 MMK for Android UI
-- Rejected --
'Su, Kotlin Basics, maybe' -> paid must be true or false, got 'maybe'
'Hla, Rust Basics, true' -> unknown course 'Rust Basics'
'broken line' -> expected 3 fields but found 1
Most active: Mya with 2 courses

Testing without stdin: scripted data and check()

Writing the input as a list inside the program means no waiting for a keyboard, and every run gives the same result, so a failure can be reproduced. check() turns an expectation into code and throws IllegalStateException with your message when it is wrong. The sample below writes small checks for one function: a valid input and two kinds of bad input.

self-checks.kt
fun parseQuantity(text: String): Result<Int> = runCatching {
    val n = text.trim().toInt()
    require(n in 1..99) { "quantity $n is outside 1..99" }
    n
}

fun expectFailure(text: String, fragment: String) {
    val message = parseQuantity(text).exceptionOrNull()?.message
    check(message != null && fragment in message) {
        "'$text' should fail with '$fragment', got $message"
    }
}

fun main() {
    check(parseQuantity(" 7 ").getOrNull() == 7) { "a padded number should parse" }
    expectFailure("0", "outside")
    expectFailure("abc", "For input string")
    println("all checks passed")
}

The program prints all checks passed. If a check were wrong, the program would stop with that message. This does not replace a real test framework such as kotlin.test, which comes in a later lesson, but it is the best first step toward trusting your own program with nothing to install.

Which slice does the next change touch?

The value of slicing shows when a change touches only one place. The table below walks through three plausible requests. Notice that the parse code does not know whether lines come from a file or from a list, so changing the input source leaves the parse untouched.

RequestSlice that changesSlices that stay
Add a discount for ADVANCED coursesSummary (and the Course data)Parse, report formatting
Read lines from a file instead of a listThe input source, outside parseParse, summary, report
Show a JSON reportReportParse, summary

In real projects

Where this shape shows up in real projects

This shape is how real data jobs are organised: an importer reads rows from a CSV file or an API, a validator turns each row into a typed record or a rejection with a reason, an aggregator computes totals, and a reporter writes a summary or sends it to a dashboard. Kotlin back ends use the same structure for order imports and payment reconciliation, and Android apps use it to turn server responses into UI state. The rejected-lines list is not a nicety. In production it is what lets someone find out why 3 of 8 records did not arrive, instead of discovering the gap in a month-end total.

Two habits carry over to real projects. Keep input handling at the edges so that the middle of the program works on typed values, and make the program able to explain itself: a count of accepted and rejected items, with reasons, is the cheapest monitoring there is.

Common mistakes

Common mistakes in a small project

Writing the whole program in main

Mix parsing, calculation and printing in one main and you cannot check a rule on its own; all you can do is read the output by eye. Make each slice a function with a typed input and output (parseEnrollment, classify, a summary function) so that a test can call it directly.

Dropping bad lines silently

mapNotNull { parseEnrollment(it).getOrNull() } is tempting, but it throws the reasons away. In this sample the three rejected lines would just vanish and the totals would look normal. Keep the failures, print them, and add the count check as well.

Accepting loose input as valid

"maybe".toBoolean() returns false, so a typo such as "ture" or any unexpected word becomes unpaid and no error appears. For something like money, a strict parser that accepts only the expected values and rejects everything else with a reason is safer.

Best practices

Best practices

  • Give each slice a named function with a typed input and output so that a test can call it.
  • Keep scripted data in one list at the top, with deliberately bad lines, so every run exercises the failure paths.
  • End main with check() calls for invariants such as no input line may vanish.
  • Put formatting helpers like Int.asMmk() in one place; changing a currency format should touch one line.

Mini challenge

Mini challenge: a gradebook report

Apply the same five slices to a different problem. A list of lines such as 'Aye:92' holds a student name and a score. Parse each line into a name and a score with Result, rejecting malformed lines and scores outside 0..100. Classify scores with a sealed interface Grade (Distinction at 85 or more, Pass at 60 or more, Fail below), keep each student's best score, and print the rejected lines with their reasons, one line per student, a count per grade and the class average as a whole number.

  • parseScore returns Result<Pair<String, Int>> and rejects a missing ':', a non-number and an out-of-range score
  • The sealed interface Grade has three data objects (Distinction, Pass, Fail) and gradeOf(score) uses a when
  • Keep each student's best score with groupBy and mapValues
  • Print the rejected lines with reasons, one line per student, a count per grade and the average
gradebook.kt
// TODO: sealed interface Grade with data objects Distinction, Pass and Fail

// TODO: 85+ is Distinction, 60+ is Pass, anything lower is Fail
fun gradeOf(score: Int): Grade {
    TODO()
}

// TODO: an exhaustive when over Grade that returns a lower-case label, with no else
fun label(grade: Grade): String {
    TODO()
}

// TODO: split on ':', require exactly two parts and a score in 0..100
fun parseScore(line: String): Result<Pair<String, Int>> {
    TODO()
}

fun main() {
    val input = listOf(
        "Aye:92", "Bo:58", "Chit:abc", "Dee:105", "Eain:74", "Bo:81", "Fay", "Gus:40",
    )

    // TODO: parse every line and print each failure as: skipped '<line>': <reason>
    // TODO: keep each student's best score and print: <name> best=<score> <label>
    // TODO: count the students per label and print the map
    // TODO: print the class average as a whole number
}

Expected: It shows the three rejected lines (Chit, Dee and Fay) with reasons, then prints Aye best=92 distinction, Bo best=81 pass, Eain best=74 pass and Gus best=40 fail. It ends with {distinction=1, pass=2, fail=1} and class average = 71.

Show hint

Keep (line, result) pairs after parsing, show failures with result.onFailure { ... }, and collect the successes with mapNotNull { (_, result) -> result.getOrNull() }. For the best score, chain scores.groupBy { it.first } into mapValues and use pairs.maxOf { it.second }. The average is values.sum() / size.

Show solution
gradebook.kt
sealed interface Grade {
    data object Distinction : Grade
    data object Pass : Grade
    data object Fail : Grade
}

fun gradeOf(score: Int): Grade = when {
    score >= 85 -> Grade.Distinction
    score >= 60 -> Grade.Pass
    else -> Grade.Fail
}

fun label(grade: Grade): String = when (grade) {
    Grade.Distinction -> "distinction"
    Grade.Pass -> "pass"
    Grade.Fail -> "fail"
}

fun parseScore(line: String): Result<Pair<String, Int>> = runCatching {
    val parts = line.split(":").map { it.trim() }
    require(parts.size == 2) { "expected name:score" }
    val score = parts[1].toInt()
    require(score in 0..100) { "score $score is outside 0..100" }
    parts[0] to score
}

fun main() {
    val input = listOf(
        "Aye:92", "Bo:58", "Chit:abc", "Dee:105", "Eain:74", "Bo:81", "Fay", "Gus:40",
    )
    val parsed = input.map { it to parseScore(it) }

    for ((raw, result) in parsed) {
        result.onFailure { println("skipped '$raw': ${it.message}") }
    }

    val scores = parsed.mapNotNull { (_, result) -> result.getOrNull() }
    val best = scores.groupBy { it.first }
        .mapValues { (_, pairs) -> pairs.maxOf { it.second } }
    for ((name, score) in best) {
        println("$name best=$score ${label(gradeOf(score))}")
    }

    val perGrade = best.values.groupBy { label(gradeOf(it)) }
        .mapValues { (_, list) -> list.size }
    println(perGrade)
    println("class average = ${best.values.sum() / best.size}")
}

Quick quiz 1 / 3

Kyaw enrolled in Android UI, so why does the report show 0 MMK revenue for it?

Quick quiz 2 / 3

What would change if mapNotNull { parseEnrollment(it).getOrNull() } replaced classify?

Quick quiz 3 / 3

What is check(accepted.size + rejected.size == script.size) { "a line was lost" } for?

What to remember

  • Split a program into model, parse, classify, summarise and report slices, each handing a typed value to the next.
  • Parse captures everything unsafe in a Result and classify turns it into the Accepted and Rejected sealed type, so every rejection has a reason.
  • The summary uses filter, groupBy, mapValues and sumOf on typed data, so it contains no parsing and cannot crash on text.
  • Scripted data and check() invariants let you verify the program repeatedly without stdin, and a lost line cannot go unnoticed.

Kotlin language guide — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Mini Project | Thuta Learning