Thuta Learning
Kotlin
ProjectsProgrammingBeginner

Practice Project: Task Manager - Part 2

KotlinLesson 3040 min

What you'll walk away with

  • Pass behaviour into a function with a lambda parameter such as predicate: (Task) -> Boolean
  • Return Task? and chain ?., ?.let and ?: instead of using !! on a lookup
  • Replace a stored immutable task with copy(), and avoid the silent bug of dropping the copy
  • Parse text commands with a when expression and toIntOrNull(), reporting bad input as a message instead of a crash

Explain it simply

Explain it simply

In Part 1 the repository could only store tasks and show them. Part 2 adds the questions people actually ask: which tasks are still open, which ones mention an invoice, mark number 3 as finished. All of those questions share one skeleton, walk the list and keep some of it, and Kotlin lets you pass the only part that changes, the rule, as a lambda.

Imagine a librarian who knows how to walk the shelves but has no idea what you want. You hand her a note saying "only the red books" or "only the cooking books", and she brings back the matches. The librarian is search(), and the note is the lambda. A receptionist, TaskManager, then reads what you typed, decides which request it is, and answers in plain text.

Problem → Why → Solution

The problem: a draft that crashes on a typo

Here is a typical first attempt at completing a task. It looks the task up with find, forces the result with !!, changes a var field and prints straight from inside the logic. The search is a hand-written loop that has to be copied for every new question.

When the user types done 42 and no such task exists, !! throws NullPointerException and the whole program stops. The loop matches only the exact case, so searching for report misses a task called Write Report. And because the function prints instead of returning text, you cannot reuse it from a test or a web page.

Draft.kt
data class Task(val id: Int, val title: String, var isDone: Boolean)

val tasks = mutableListOf(Task(1, "Write Report", false))

fun complete(id: Int) {
    val task = tasks.find { it.id == id }!!
    task.isDone = true
    println("Completed ${task.title}")
}

fun searchByText(text: String): List<Task> {
    val result = mutableListOf<Task>()
    for (task in tasks) {
        if (task.title.contains(text)) result.add(task)
    }
    return result
}

fun main() {
    println(searchByText("report").size)
    complete(1)
    complete(42)
}

Why is this fragile?

!! tells the compiler to trust you that the value is never null, and the compiler does. The moment the lookup returns null, that promise breaks at run time, far from the code that made it. Copy-pasted loops also drift apart: one gets ignoreCase, another does not. A lambda parameter keeps the walking in one place, and a nullable return type turns not found into something every caller has to handle.

Core concept: pass the rule, handle the absence

Part 2 rests on five small ideas that fit together: passing rules as lambdas, treating absence as a value, replacing immutable data, branching with when, and keeping logic apart from printing. The TaskManager class combines all of them in about fifty lines.

1. A lambda is a value you can pass

search(predicate: (Task) -> Boolean) means the parameter is itself a function that takes a Task and answers true or false. The repository owns the walking and the caller owns the rule. Write the call as repo.search { it.priority == priority }: when the last parameter is a function, the lambda may sit outside the parentheses, and a lambda with one parameter can refer to it as it. One search() replaces a whole family of byPriority, byText and pendingOnly functions.

2. Absence is a value, not a crash

complete(id) returns Task?, where null means no such task. The caller chains ?.let { ... } to run code only when something was found and ?: to supply the fallback otherwise. Keep !! for values you have proven non-null, and data typed by a user is never in that group. toIntOrNull() follows the same idea: it returns null for done abc, where toInt() would throw NumberFormatException.

3. Immutable means replace, not edit

complete() finds the position with indexOfFirst, builds tasks[index].copy(isDone = true) and writes it back with tasks[index] = completed. Calling copy() alone changes nothing, because the result is a new object that has to be stored. The position -1 means no match, so the function returns null before touching the list.

4. when turns a word into a branch

execute() reads the first word and uses when as an expression. Each branch produces a String, the else branch is mandatory, and a new command later is one new line. The rest of the input comes from split(" ", limit = 3), which keeps the title together as the third element even when it contains spaces.

5. Logic returns text, main prints it

execute() returns a String instead of printing. Anything can call it now: main prints the reply, a test compares it with an expected string, and a web page could show it. The scripted list of commands in main replaces keyboard input, so every run prints identical output.

OperatorMeaningUsed here
?.Call only when the value is not nullidText?.toIntOrNull()
?:Use the right side when the left is null?: return "Usage: done <id>"
?.let { }Run a block only for a non-null valuerepo.complete(id)?.let { ... }
!!Assert non-null, throws NullPointerExceptionAvoided for user data
Mental model: ask the question, pass the rule
  1. Read the command word
  2. Pick the branch with when
  3. Pass the rule as a lambda
  4. Return text, null means not found

The repository knows how to walk the list; the caller decides what to keep.

General pattern

kotlin
class Store {
    fun pick(rule: (Item) -> Boolean): List<Item> = items.filter(rule)
}

val hits = store.pick { it.name.length > 3 }

val number = text?.toIntOrNull() ?: return "usage"

val reply = when (word) {
    "go" -> "going"
    else -> "unknown"
}

Pass the rule as a function-typed parameter, chain ?. and ?: when a value may be missing, and let when pick one branch from a word.

Part 2 code: lambdas, null safety and a command interpreter

This is the full Part 2 program, and the highlighted lines are the new ones: complete() and search() in the repository, the whole TaskManager, and the scripted main. Priority, Task and the rest of TaskRepository are exactly as in Part 1. Read the output against the script. Every command is echoed after a > and then answered, including the ones that go wrong on purpose: an unknown priority, a missing id, text that is not a number, and an unknown command.

TaskManager.kt
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()
}

class TaskManager(private val repo: TaskRepository) {

    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(" "))
            "" -> "Type a command: add, done, list or find"
            else -> "Unknown command '${parts[0]}'"
        }
    }

    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) }
}

fun main() {
    val manager = TaskManager(TaskRepository())
    val script = listOf(
        "add high Review Kotlin syntax",
        "add medium Practice data classes",
        "add HIGH Practice lambdas",
        "add urgent Fix the build",
        "add low",
        "done 1",
        "done 42",
        "done abc",
        "list",
        "list high",
        "find PRACTICE",
        "find zebra",
        "archive 3",
    )
    for (command in script) {
        println("> $command")
        println(manager.execute(command))
    }
}

Code breakdown

  1. A function-typed parameterfun search(predicate: (Task) -> Boolean): List<Task> = tasks.filter(predicate)

    (Task) -> Boolean is the type of a function that takes a Task and returns a Boolean. filter accepts exactly that type, so search simply forwards the caller's rule.

  2. Replace the immutable tasktasks[index] = completed

    Because Task is immutable, complete() writes the changed copy back into the same position. Without this assignment the copy would be thrown away and the task would stay open. indexOfFirst returns -1 when nothing matches, which is why an earlier line returns null.

  3. One word picks a branchreturn when (parts[0].lowercase()) {

    lowercase() makes ADD and add the same command. when is used as an expression here, so every branch must produce a String and the else branch is required.

  4. Keep the title in one pieceval parts = line.trim().split(" ", limit = 3)

    limit = 3 stops splitting after two cuts, so add high Review Kotlin syntax becomes add, high and Review Kotlin syntax. trim() first removes spaces at both ends of the line.

  5. Parse without crashingval id = idText?.toIntOrNull() ?: return "Usage: done <id>"

    If idText is null (nothing was typed) or is not a number, the whole chain is null and the Elvis branch returns early with a usage message. The next line can then use id as a plain Int.

  6. Absence as a fallback?.let { "Completed " + format(it) }

    ?.let runs only when complete() found a task, and the ?: on the next line supplies the fallback text, which is how done 42 prints No task with id 42.

  7. Priorities from textPriority.entries.firstOrNull { it.name.equals(text, ignoreCase = true) }

    Priority.valueOf would throw for an unknown name; firstOrNull returns null instead, so urgent becomes an Unknown priority message. equals with ignoreCase = true accepts HIGH, high and High.

You should see
> 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
Added [ ] #3 Practice lambdas (HIGH)
> add urgent Fix the build
Unknown priority 'urgent'
> add low
Usage: add <low|medium|high> <title>
> done 1
Completed [x] #1 Review Kotlin syntax (HIGH)
> done 42
No task with id 42
> done abc
Usage: done <id>
> list
[x] #1 Review Kotlin syntax (HIGH)
[ ] #2 Practice data classes (MEDIUM)
[ ] #3 Practice lambdas (HIGH)
> list high
[x] #1 Review Kotlin syntax (HIGH)
[ ] #3 Practice lambdas (HIGH)
> find PRACTICE
[ ] #2 Practice data classes (MEDIUM)
[ ] #3 Practice lambdas (HIGH)
> find zebra
(no matching tasks)
> archive 3
Unknown command 'archive'

One search, many questions

Because search takes the rule as a parameter, a new question needs no new function in the repository. The snippet passes lambdas in both allowed styles, inside the parentheses with a named parameter and outside as a trailing lambda, and shows that an empty list simply gives an empty result.

Lambdas.kt
data class Task(val id: Int, val title: String, val isDone: Boolean)

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

fun main() {
    val tasks = listOf(
        Task(1, "Pay rent", true),
        Task(2, "Call Ko Aung", false),
        Task(3, "Send the monthly invoice", false),
    )
    val pending = pick(tasks) { !it.isDone }
    val longTitles = pick(tasks, { task -> task.title.length > 10 })
    val nothing = pick(emptyList()) { true }
    println(pending.map { it.id })
    println(longTitles.map { it.title })
    println(nothing)
}

pick(tasks) { !it.isDone } uses it, the implicit name for a lone parameter. The second call names the parameter task, which reads better once a rule gets longer. Neither call can fail on an empty list, because filter just returns an empty list.

?. and ?: versus !!

The same missing value can be handled three ways. ?. skips the call and gives null, ?: replaces null with a fallback, and !! gives up and throws. The snippet runs all of them against one id that exists and one that does not.

NullHandling.kt
fun findTitle(titles: Map<Int, String>, id: Int): String? = titles[id]

fun main() {
    val titles = mapOf(1 to "Write report", 2 to "Call Ko Aung")
    println(findTitle(titles, 2)?.uppercase())
    println(findTitle(titles, 9)?.uppercase())
    println(findTitle(titles, 9) ?: "no such task")
    try {
        println(findTitle(titles, 9)!!.uppercase())
    } catch (e: NullPointerException) {
        println("!! threw ${e::class.simpleName}")
    }
}

The missing id prints null with ?., no such task with ?:, and with !! it throws NullPointerException, which the snippet catches only so the output can continue. In the Task Manager nothing catches it, so one mistyped id would end the session.

The silent copy() bug

A data class makes it easy to forget that copy() returns a new object. The snippet prints false after calling copy on its own line, because the result was dropped, and true only after the copy is stored back into the list.

SilentCopy.kt
data class Task(val id: Int, val title: String, val isDone: Boolean = false)

fun main() {
    val tasks = mutableListOf(Task(1, "Write report"))

    tasks[0].copy(isDone = true)
    println("after copy only: ${tasks[0].isDone}")

    tasks[0] = tasks[0].copy(isDone = true)
    println("after storing the copy: ${tasks[0].isDone}")
}

In real projects

In real projects

Predicate parameters are everywhere in real Kotlin code. Android developers filter the lists shown on screen with the same filter { } calls, server code passes lambdas to database helpers and retry wrappers, and the standard library itself is built from them: filter, map, sortedBy, any and all all take a function. Writing your own function that accepts a lambda is the same skill used one level up.

The command interpreter is a small version of a route table. A web framework looks at the HTTP method and path, calls the matching handler and returns a response, and a chatbot or a Slack bot reads a word and picks an action in just the same way. Because execute() returns text and never touches the keyboard, it can be tested by comparing strings, which is also how production handlers are usually tested.

Common mistakes

Common mistakes

Using !! on a lookup

tasks.find { ... }!! works until a user types an id that does not exist, and then the program stops with a NullPointerException. Return Task? and let the caller decide, or use ?: with a clear message.

Calling copy() and dropping the result

tasks[index].copy(isDone = true) on a line of its own compiles and changes nothing, because the copy is a new object that nobody stored. Assign it back with tasks[index] = completed, and print the list afterwards to be sure.

Using toInt() on text a user typed

toInt() throws NumberFormatException for done abc, so a single typo ends the session. toIntOrNull() returns null instead, and the Elvis operator turns that null into a usage message.

Forgetting else, or the lowercase()

A when expression used as a value on a String subject needs an else branch, and leaving it out is a compile error. Comparing the raw first word also makes ADD an unknown command until you call lowercase().

Mini challenge

Three list helpers with edge cases

Write three extension functions on List<Task> and test them with empty and blank inputs: pending(priority) returns tasks that are not done, optionally for one priority; matching(text) finds titles containing the text, ignoring case; titlesOrNone() joins titles with commas or returns (none).

  • pending() takes an optional Priority? = null, where null means any priority
  • matching() ignores case and returns an empty list for blank text instead of every task
  • titlesOrNone() prints (none) for an empty list, so the output is never an empty string
  • main tests a normal case, an empty list and a blank search
Challenge.kt
// Reuse Priority and Task from the lesson.

fun List<Task>.pending(priority: Priority? = null): List<Task> {
    // TODO: keep tasks that are not done; when priority is not null,
    //       keep only tasks with that priority
}

fun List<Task>.matching(text: String): List<Task> {
    // TODO: trim the text and return an empty list when nothing is left,
    //       otherwise keep titles that contain it, ignoring case
}

fun List<Task>.titlesOrNone(): String {
    // TODO: "(none)" for an empty list, otherwise the titles joined with ", "
}

fun main() {
    // TODO: build four tasks (one already done) and print pending(),
    //       pending(Priority.HIGH), matching("REPORT"), matching("  ")
    //       and pending() on an empty list
}

Expected: pending lists three titles, pending HIGH lists Send invoice, pending LOW lists Report bug to vendor, matching REPORT lists two titles, and both the blank search and the empty list print (none).

Show hint

filter { ... } takes the rule as a lambda; inside it combine !it.isDone with (priority == null || it.priority == priority). For matching, trim the text first and return emptyList() when nothing is left.

Show solution
Challenge.kt
enum class Priority { LOW, MEDIUM, HIGH }

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

fun List<Task>.pending(priority: Priority? = null): List<Task> =
    filter { !it.isDone && (priority == null || it.priority == priority) }

fun List<Task>.matching(text: String): List<Task> {
    val needle = text.trim()
    if (needle.isEmpty()) return emptyList()
    return filter { it.title.contains(needle, ignoreCase = true) }
}

fun List<Task>.titlesOrNone(): String =
    if (isEmpty()) "(none)" else joinToString(", ") { it.title }

fun main() {
    val tasks = listOf(
        Task(1, "Write report", Priority.HIGH, isDone = true),
        Task(2, "Call Ko Aung", Priority.MEDIUM),
        Task(3, "Send invoice", Priority.HIGH),
        Task(4, "Report bug to vendor", Priority.LOW),
    )
    println("pending: ${tasks.pending().titlesOrNone()}")
    println("pending HIGH: ${tasks.pending(Priority.HIGH).titlesOrNone()}")
    println("pending LOW: ${tasks.pending(Priority.LOW).titlesOrNone()}")
    println("matching 'REPORT': ${tasks.matching("REPORT").titlesOrNone()}")
    println("matching blank: ${tasks.matching("   ").titlesOrNone()}")
    println("empty list: ${emptyList<Task>().pending().titlesOrNone()}")
}

Quick quiz 1 / 3

In repo.search { it.priority == priority }, what is the part inside the braces?

Quick quiz 2 / 3

idText is "abc". What happens at: val id = idText?.toIntOrNull() ?: return "Usage: done <id>"?

Quick quiz 3 / 3

Task is an immutable data class. Which line really marks task 1 as done inside the repository's list?

What to remember

  • A function-typed parameter such as (Task) -> Boolean lets the caller supply the rule while the repository owns the loop
  • Return Task? and use ?., ?.let and ?: instead of !! for data that can be missing
  • With immutable data, store the result of copy(); calling copy() alone changes nothing
  • when as an expression plus toIntOrNull() turns text commands into safe branches

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 2 | Thuta Learning