Thuta Learning
Kotlin
ProjectsProgrammingBeginner

Practice Project: Task Manager - Part 3

KotlinLesson 3145 min

What you'll walk away with

  • Declare an interface with a default method and implement it with override
  • Group, count and sort tasks with groupBy, count and sortedWith, including an explicit tie-break
  • Compute a percentage safely: Double division, rounding, and a guard for an empty list
  • Write and read a one-line-per-task file defensively, skipping damaged lines instead of crashing

Explain it simply

Explain it simply

This is the finishing lesson. The Task Manager already adds, completes and searches. Now it learns to report on itself and to remember its tasks after the program stops. A report answers questions such as how much is done and what should I do next, and a saved file lets tomorrow's run continue where today's ended.

Think of a shop owner at closing time. She counts the day's sales, writes a short summary for her partner, and files the receipts in a drawer. Next morning she opens the drawer and carries on, even if one receipt is smudged and unreadable: she sets that one aside instead of closing the shop. The summary is the Reportable interface, the drawer is a file, and setting the smudged receipt aside is the defensive reader.

Problem → Why → Solution

The problem: a loader that trusts the file

Persistence is where first drafts hurt most. The draft below shows the loader people usually write first: split on the pipe, call toInt() and valueOf(), and map the whole list. It works on a file the program itself just wrote, so the demo passes.

Real files are messier. A line that is not a task, a priority someone edited to URGENT, or a title that contains the separator character itself makes the loader throw, and one bad line loses every other task. The report code has the same temperament: integer division by zero throws ArithmeticException, so a percentage computed on an empty list ends the program.

LoaderDraft.kt
enum class Priority { LOW, MEDIUM, HIGH }

data class Task(val id: Int, val title: String, val priority: Priority)

// File format: id|title|priority
fun loadDraft(lines: List<String>): List<Task> =
    lines.map { line ->
        val parts = line.split("|")
        Task(parts[0].toInt(), parts[1], Priority.valueOf(parts[2]))
    }

fun main() {
    val samples = listOf(
        "1|Pay rent|HIGH",   // fine
        "oops",              // not a task at all
        "7|Fix|URGENT",      // priority edited by hand
        "3|a|b|HIGH",        // the title contains the separator
    )
    for (line in samples) {
        try {
            println(loadDraft(listOf(line)))
        } catch (e: Exception) {
            println("${e::class.simpleName}: ${e.message}")
        }
    }
}

Why does one bad line ruin everything?

map applies the parsing to every line, and any exception escapes from the middle of it, so the caller receives nothing at all. toInt() and valueOf() both report bad input by throwing, which is right for a programming mistake but wrong for data read from outside the program. Data from a disk or a network must be treated as untrusted: parse each line into a Task? and decide what to do with the failures.

Core concept: contracts, careful maths and a defensive reader

Part 3 adds the last layer to the Task Manager. Each of the four ideas below solves a problem that only appears once the program is used for real: more than one kind of report, ties and empty data in the numbers, and a file that someone else may edit.

1. An interface is a promise

interface Reportable declares summary() and gives printSummary() a default body built on top of it. A class that says : Reportable must supply summary() and mark it override, and forgetting the keyword is a compile error. Anything that holds a Reportable can ask for a summary without knowing whether it is looking at a TaskManager or something else, which is why the challenge adds a second implementation.

2. A report is group, count and sort

groupBy { it.priority } returns a Map<Priority, List<Task>> that only has keys which actually occur, so the report loops over Priority.entries and uses orEmpty() to show levels with zero tasks. For the open-task list, sortedWith(compareByDescending<Task> { it.priority }.thenBy { it.id }) states the tie-break outright instead of relying on how a sort happens to treat equal elements.

3. Percentages: multiply as Double, divide last, guard zero

done * 100.0 / total keeps the division in Double, and roundToInt() turns 33.3 into 33. done / total * 100 divides two Ints first and gives 0 until every task is done. An empty list needs its own early return, because dividing by zero is an ArithmeticException for Int and a NaN for Double, and NaN cannot be rounded.

4. Files: write one line per task, read defensively

TaskStore writes id|priority|isDone|title with the free-text title last, and reads it back with split("|", limit = 4), so a title that contains a pipe survives. decode() returns Task?, every failure path returns null, and mapNotNull keeps the good lines while load() counts the rest as skipped. replaceAll() then restarts nextId after the largest loaded id, so new tasks never collide with old ones.

Edge caseHow the code handles itResult
No tasks at allsummary() returns earlyNo tasks yet
Title contains |Title is last, split(limit = 4)Title read back intact
Damaged or hand-edited linedecode() returns nullSkipped and counted
Restart after loadingnextId = largest id + 1No duplicate ids
Mental model: report, save, read defensively
  1. Write the contract (Reportable)
  2. Group, count and sort the data
  3. Save one line per task
  4. Read defensively: skip, never crash

Your own output can be trusted; anything read back from outside cannot.

General pattern

kotlin
interface Reportable {
    fun summary(): String
    fun printSummary() = println(summary())
}

class Manager : Reportable {
    override fun summary(): String = "..."
}

val groups = items.groupBy { it.kind }
val ordered = items.sortedWith(compareByDescending<Item> { it.rank }.thenBy { it.id })
val parts = line.split("|", limit = 3)

An interface states what a class promises to do, groupBy and sortedWith shape data for a report, and split with a limit keeps the last field intact when it may contain the separator.

Part 3 code: the finished Task Manager

This is the complete program, and the highlighted lines are new in Part 3: the imports, replaceAll() in the repository, the Reportable interface, the report command and summary(), the TaskStore, and the scripted main. main writes the tasks to a file inside a temporary directory, appends two damaged lines to imitate a hand-edited file, loads it back, and cleans up in finally, so nothing is left behind and no path is ever printed.

TaskManager.kt
import java.nio.file.Files
import java.nio.file.Path
import kotlin.math.roundToInt

enum class Priority { LOW, MEDIUM, HIGH }

data class Task(
    val id: Int,
    val title: String,
    val priority: Priority,
    val isDone: Boolean = false,
)

class TaskRepository {
    private val tasks = mutableListOf<Task>()
    private var nextId = 1

    fun add(title: String, priority: Priority = Priority.MEDIUM): Task {
        require(title.isNotBlank()) { "Task title must not be blank" }
        val task = Task(id = nextId++, title = title.trim(), priority = priority)
        tasks.add(task)
        return task
    }

    fun findById(id: Int): Task? = tasks.firstOrNull { it.id == id }

    fun complete(id: Int): Task? {
        val index = tasks.indexOfFirst { it.id == id }
        if (index == -1) return null
        val completed = tasks[index].copy(isDone = true)
        tasks[index] = completed
        return completed
    }

    fun search(predicate: (Task) -> Boolean): List<Task> = tasks.filter(predicate)

    fun all(): List<Task> = tasks.toList()

    fun replaceAll(restored: List<Task>) {
        tasks.clear()
        tasks.addAll(restored)
        nextId = (restored.maxOfOrNull { it.id } ?: 0) + 1
    }
}

interface Reportable {
    fun summary(): String

    fun printSummary() = println(summary())
}

class TaskManager(private val repo: TaskRepository) : Reportable {

    fun execute(line: String): String {
        val parts = line.trim().split(" ", limit = 3)
        return when (parts[0].lowercase()) {
            "add" -> add(parts.getOrNull(1), parts.getOrNull(2))
            "done" -> done(parts.getOrNull(1))
            "list" -> list(parts.getOrNull(1))
            "find" -> find(parts.drop(1).joinToString(" "))
            "report" -> summary()
            "" -> "Type a command: add, done, list, find or report"
            else -> "Unknown command '${parts[0]}'"
        }
    }

    override fun summary(): String {
        val tasks = repo.all()
        if (tasks.isEmpty()) return "No tasks yet"
        val byPriority = tasks.groupBy { it.priority }
        val lines = mutableListOf("=== Task summary ===")
        for (priority in Priority.entries.reversed()) {
            val group = byPriority[priority].orEmpty()
            val finished = group.count { it.isDone }
            lines += "${priority.name.padEnd(6)} $finished/${group.size} done"
        }
        val doneCount = tasks.count { it.isDone }
        lines += "Completed: ${(doneCount * 100.0 / tasks.size).roundToInt()}%"
        lines += "--- Still open, most urgent first ---"
        val open = tasks.filter { !it.isDone }
            .sortedWith(compareByDescending<Task> { it.priority }.thenBy { it.id })
        lines += if (open.isEmpty()) listOf("(nothing left)") else open.map { format(it) }
        return lines.joinToString("\n")
    }

    private fun add(priorityText: String?, title: String?): String {
        if (priorityText == null || title.isNullOrBlank()) {
            return "Usage: add <low|medium|high> <title>"
        }
        val priority = parsePriority(priorityText)
            ?: return "Unknown priority '$priorityText'"
        return "Added " + format(repo.add(title, priority))
    }

    private fun done(idText: String?): String {
        val id = idText?.toIntOrNull() ?: return "Usage: done <id>"
        return repo.complete(id)
            ?.let { "Completed " + format(it) }
            ?: "No task with id $id"
    }

    private fun list(priorityText: String?): String {
        if (priorityText == null) return render(repo.all())
        val priority = parsePriority(priorityText)
            ?: return "Unknown priority '$priorityText'"
        return render(repo.search { it.priority == priority })
    }

    private fun find(text: String): String {
        if (text.isBlank()) return "Usage: find <text>"
        return render(repo.search { it.title.contains(text, ignoreCase = true) })
    }

    private fun parsePriority(text: String?): Priority? =
        Priority.entries.firstOrNull { it.name.equals(text, ignoreCase = true) }

    private fun format(task: Task): String {
        val mark = if (task.isDone) "[x]" else "[ ]"
        return "$mark #${task.id} ${task.title} (${task.priority})"
    }

    private fun render(tasks: List<Task>): String =
        if (tasks.isEmpty()) "(no matching tasks)"
        else tasks.joinToString("\n") { format(it) }
}

data class LoadResult(val tasks: List<Task>, val skipped: Int)

class TaskStore(private val file: Path) {

    fun save(tasks: List<Task>) {
        val lines = tasks.map { "${it.id}|${it.priority}|${it.isDone}|${it.title}" }
        Files.write(file, lines)
    }

    fun load(): LoadResult {
        if (!Files.exists(file)) return LoadResult(emptyList(), 0)
        val lines = Files.readAllLines(file).filter { it.isNotBlank() }
        val tasks = lines.mapNotNull { decode(it) }
        return LoadResult(tasks, lines.size - tasks.size)
    }

    private fun decode(line: String): Task? {
        val parts = line.split("|", limit = 4)
        if (parts.size != 4) return null
        val id = parts[0].toIntOrNull() ?: return null
        val priority = Priority.entries.firstOrNull { it.name == parts[1] } ?: return null
        val isDone = parts[2].toBooleanStrictOrNull() ?: return null
        return Task(id, parts[3], priority, isDone)
    }
}

fun main() {
    val dir = Files.createTempDirectory("taskmanager-")
    val file = dir.resolve("tasks.txt")
    try {
        val repo = TaskRepository()
        val manager = TaskManager(repo)
        manager.printSummary()
        listOf(
            "add high Review Kotlin syntax",
            "add medium Practice data classes",
            "add high Practice lambdas | pipes are fine",
            "add low Learn interfaces",
            "add high Finish the project",
            "done 1",
            "done 3",
        ).forEach { println("> $it"); println(manager.execute(it)) }
        manager.printSummary()

        val store = TaskStore(file)
        store.save(repo.all())
        println("Saved ${Files.readAllLines(file).size} tasks")

        val damage = "oops|not a task\n9|URGENT|false|Bad\n"
        Files.writeString(file, Files.readString(file) + damage)
        val loaded = store.load()
        println("Loaded ${loaded.tasks.size}, skipped ${loaded.skipped} damaged lines")

        val restored = TaskRepository().apply { replaceAll(loaded.tasks) }
        println(TaskManager(restored).execute("add low Write the next lesson"))
    } finally {
        Files.deleteIfExists(file)
        Files.deleteIfExists(dir)
    }
}

Code breakdown

  1. Interface with a default methodfun printSummary() = println(summary())

    printSummary() has a body, so implementers get it for free and only write summary(). TaskManager overrides summary(), and main calls printSummary() twice: once on an empty manager and once after the tasks exist.

  2. Show empty levels tooval group = byPriority[priority].orEmpty()

    groupBy creates only the keys that occur. Looking up a missing key gives null, and orEmpty() turns that into an empty list, so a level with no tasks would print 0/0 done instead of crashing.

  3. Stable ordering.sortedWith(compareByDescending<Task> { it.priority }.thenBy { it.id })

    Highest priority first, and tasks with the same priority in creation order. The report therefore shows #5 (HIGH) before #2 (MEDIUM) before #4 (LOW).

  4. Percentage on Doubleslines += "Completed: ${(doneCount * 100.0 / tasks.size).roundToInt()}%"

    Two done out of five is 40.0 after the Double division, and roundToInt() makes it 40. The empty-list case never reaches this line because summary() has already returned early.

  5. Free-text field goes lastval parts = line.split("|", limit = 4)

    At most four parts are produced, so everything after the third pipe stays in the title. Task 3's title contains a pipe and survives the round trip.

  6. Null means skipval id = parts[0].toIntOrNull() ?: return null

    Each failure path in decode() returns null instead of throwing. load() keeps the good lines with mapNotNull and counts the rest as skipped, which here are oops|not a task and the URGENT line.

  7. Cleanup in finallyFiles.deleteIfExists(file)

    The temporary file and directory are removed even if something above throws. The directory is deleted last because it has to be empty first.

You should see
No tasks yet
> add high Review Kotlin syntax
Added [ ] #1 Review Kotlin syntax (HIGH)
> add medium Practice data classes
Added [ ] #2 Practice data classes (MEDIUM)
> add high Practice lambdas | pipes are fine
Added [ ] #3 Practice lambdas | pipes are fine (HIGH)
> add low Learn interfaces
Added [ ] #4 Learn interfaces (LOW)
> add high Finish the project
Added [ ] #5 Finish the project (HIGH)
> done 1
Completed [x] #1 Review Kotlin syntax (HIGH)
> done 3
Completed [x] #3 Practice lambdas | pipes are fine (HIGH)
=== Task summary ===
HIGH   2/3 done
MEDIUM 0/1 done
LOW    0/1 done
Completed: 40%
--- Still open, most urgent first ---
[ ] #5 Finish the project (HIGH)
[ ] #2 Practice data classes (MEDIUM)
[ ] #4 Learn interfaces (LOW)
Saved 5 tasks
Loaded 5, skipped 2 damaged lines
Added [ ] #6 Write the next lesson (LOW)

Integer division and rounding

The percentage line is a small example of a very common family of bugs. The snippet shows the two wrong orders of operations, a safe helper, and what a zero denominator does to Int division.

Percent.kt
import kotlin.math.roundToInt

fun percentDone(done: Int, total: Int): Int =
    if (total == 0) 0 else (done * 100.0 / total).roundToInt()

fun main() {
    println(2 / 3 * 100)
    println(2 * 100 / 3)
    println(percentDone(2, 3))
    println(percentDone(1, 3))
    println(percentDone(0, 0))
    val zero = 0
    try {
        println(5 / zero)
    } catch (e: ArithmeticException) {
        println("${e::class.simpleName}: ${e.message}")
    }
}

2 / 3 * 100 prints 0 because 2 / 3 is an Int division that gives 0 before the multiplication happens, and 2 * 100 / 3 prints 66 because the fraction is cut off rather than rounded. percentDone(2, 3) rounds to 67, and percentDone(0, 0) answers 0 by guarding the empty case. The last line shows the exception that Int division by zero throws.

Testing the file format without a framework

You do not need a test library to start testing. check(condition) { message } throws IllegalStateException when the condition is false, so a plain main can assert behaviour. The snippet round-trips three titles, including one with pipes and one with Myanmar text, and then confirms that six kinds of bad lines are rejected.

RoundTrip.kt
enum class Priority { LOW, MEDIUM, HIGH }

data class Task(
    val id: Int,
    val title: String,
    val priority: Priority,
    val isDone: Boolean,
)

fun encode(t: Task): String = "${t.id}|${t.priority}|${t.isDone}|${t.title}"

fun decode(line: String): Task? {
    val parts = line.split("|", limit = 4)
    if (parts.size != 4) return null
    val id = parts[0].toIntOrNull() ?: return null
    val priority = Priority.entries.firstOrNull { it.name == parts[1] } ?: return null
    val isDone = parts[2].toBooleanStrictOrNull() ?: return null
    return Task(id, parts[3], priority, isDone)
}

fun main() {
    val samples = listOf(
        Task(1, "Plain title", Priority.LOW, false),
        Task(2, "Title | with | pipes", Priority.HIGH, true),
        Task(3, "Ünïcode and မြန်မာ", Priority.MEDIUM, false),
    )
    for (t in samples) {
        check(decode(encode(t)) == t) { "round trip failed for $t" }
        println("round trip ok: #${t.id}")
    }
    val bad = listOf(
        "", "oops", "1|URGENT|false|x", "1|LOW|maybe|x", "x|LOW|false|x", "1|LOW|false",
    )
    for (line in bad) {
        check(decode(line) == null) { "should reject: '$line'" }
    }
    println("rejected ${bad.size} bad lines")
}

If any check failed, the program would stop with the message you wrote. Real projects move such assertions into kotlin.test, which the testing lesson earlier in this tutorial covers, but the habit is the same: for every format you write, test one normal case, one tricky case and several bad inputs.

Why the override keyword is mandatory

If a class implements an interface function without override, the compiler refuses it. The snippet below is deliberately incomplete code, so it is marked as not runnable here.

MissingOverride.kt
interface Reportable {
    fun summary(): String
}

class Sprint : Reportable {
    fun summary(): String = "Sprint 1"
}

fun main() {
    println(Sprint().summary())
}

Compiling it stops with: 'summary' hides member of supertype 'Reportable' and needs an 'override' modifier. The keyword protects both sides: it stops you from hiding an interface function with one that merely has the same name, and it makes the compiler complain if the interface later renames or removes the function you thought you were overriding.

In real projects

In real projects

Interfaces like Reportable are how real codebases keep parts replaceable. A payment service depends on a PaymentGateway interface and tests supply a fake one, and a report generator depends on a small interface instead of a database class. The Task Manager's report could be printed, written to a file or e-mailed by three different Reportable implementations without changing the code that asks for a summary.

Persistence carries the same lesson at a larger scale. Whether the data lives in a text file, JSON, SQLite or a remote API, anything read from outside the program is untrusted: files get edited by hand, formats change between versions, and uploads arrive half finished. Production loaders therefore validate each record, keep the good ones, report the bad ones and log how many were skipped, just as TaskStore.load() does. Writing temporary files into a temporary directory and deleting them in finally is also the normal way to keep tests from leaving garbage behind.

Common mistakes

Common mistakes

Forgetting override

Implementing an interface function without override is a compile error, not a warning: 'summary' hides member of supertype 'Reportable' and needs an 'override' modifier. Add the keyword, and let the IDE generate the stub if you are unsure of the signature.

Dividing before multiplying

done / total * 100 divides two Ints first, so 2 of 3 gives 0 and only a fully finished list ever reports a percentage. Multiply with a Double first, as in done * 100.0 / total, and handle total == 0 separately.

A loader that trusts the file

split("|") with toInt() and valueOf() throws on the first damaged line, and a title that contains a pipe shifts every field after it. Put the free text last, use split with a limit, return null from decode() for each failure, and report how many lines were skipped.

Restarting ids after loading

If the repository starts nextId at 1 again after a load, the first new task collides with a stored one. Set nextId to the largest loaded id plus one, which replaceAll() does, and prove it with a task added right after loading.

Best practices

Ideas for taking the project further

  • Replace the text file with JSON (kotlinx.serialization) or SQLite, keeping TaskStore's save and load signatures so nothing else changes.
  • Add a due date with java.time.LocalDate and a report of overdue tasks.
  • Move the round-trip checks from the snippet into kotlin.test and run them from Gradle.
  • Add a second front end, such as a tiny HTTP handler, that calls TaskManager.execute() exactly as main does.

Mini challenge

A second Reportable: sprint summaries

Implement Reportable a second time with a Sprint class that holds a name and a list of tasks. Its summary() reports how many tasks are done with a rounded percentage and names the most urgent open task. Handle an empty sprint and a fully finished sprint.

  • Sprint implements Reportable and marks summary() with override
  • summary() prints the done count, the total and a rounded percentage using Double division
  • The next task is the open task with the highest priority, ties broken by the lowest id
  • An empty sprint prints no tasks, and a finished sprint says that nothing is left
  • main keeps the sprints in a List<Reportable> and calls printSummary() on each
Challenge.kt
// Reuse Priority, Task and Reportable from the lesson.

class Sprint(private val name: String, private val tasks: List<Task>) : Reportable {
    override fun summary(): String {
        // TODO: "Sprint <name>: no tasks" for an empty list
        // TODO: done count, total and the rounded percentage
        // TODO: the open task with the highest priority (ties: lowest id)
        return ""
    }
}

fun main() {
    // TODO: build one normal sprint, one empty sprint and one finished sprint,
    //       put them in a List<Reportable> and call printSummary() on each
}

Expected: Alpha reports 1 of 4 done (25%) and Next up: Fix crash on start, Beta reports no tasks, and Gamma reports 1 of 1 done (100%) and that the sprint is complete.

Show hint

Filter the open tasks, sort them with sortedWith(compareByDescending<Task> { it.priority }.thenBy { it.id }) and take firstOrNull(). Use next?.title ?: for the finished case, and return early for an empty list before any division.

Show solution
Challenge.kt
import kotlin.math.roundToInt

enum class Priority { LOW, MEDIUM, HIGH }

data class Task(
    val id: Int,
    val title: String,
    val priority: Priority,
    val isDone: Boolean = false,
)

interface Reportable {
    fun summary(): String

    fun printSummary() = println(summary())
}

class Sprint(private val name: String, private val tasks: List<Task>) : Reportable {
    override fun summary(): String {
        if (tasks.isEmpty()) return "Sprint $name: no tasks"
        val done = tasks.count { it.isDone }
        val percent = (done * 100.0 / tasks.size).roundToInt()
        val next = tasks.filter { !it.isDone }
            .sortedWith(compareByDescending<Task> { it.priority }.thenBy { it.id })
            .firstOrNull()
        return "Sprint $name: $done of ${tasks.size} done ($percent%)\n" +
            "Next up: ${next?.title ?: "nothing, the sprint is complete"}"
    }
}

fun main() {
    val sprints: List<Reportable> = listOf(
        Sprint(
            "Alpha",
            listOf(
                Task(1, "Design login", Priority.MEDIUM, isDone = true),
                Task(2, "Fix crash on start", Priority.HIGH),
                Task(3, "Update icons", Priority.HIGH),
                Task(4, "Write release notes", Priority.LOW),
            ),
        ),
        Sprint("Beta", emptyList()),
        Sprint("Gamma", listOf(Task(7, "Ship it", Priority.HIGH, isDone = true))),
    )
    sprints.forEach { it.printSummary() }
}

Quick quiz 1 / 3

class Sprint : Reportable declares fun summary(): String = "..." without the override keyword. What happens?

Quick quiz 2 / 3

val done = 2 and val total = 3. What does println(done / total * 100) print?

Quick quiz 3 / 3

What does "7|HIGH|true|Call A|B".split("|", limit = 4) produce?

What to remember

  • An interface declares what a class promises, can include default methods, and every implementation must be marked override
  • Build reports from groupBy, count and sortedWith, state the tie-break, and loop over enum entries to show empty groups
  • Multiply by 100.0 before dividing, round last, and return early when the list is empty
  • Read files defensively: free text last, split with a limit, null for bad lines, and restart ids after the largest loaded id

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.

Practice Project: Task Manager - Part 3 | Thuta Learning