Skip to content
Tutorials Center
My learning

Topics

Lesson 123 of 134 ยท Projects

Project: Command-Line To-Do Manager

Build a to-do manager in Kotlin step by step - immutable data classes, a sealed command parser, a repository interface, text persistence and a full interactive loop you can run in your browser.

A to-do list is the perfect second project. The idea is simple, but it forces you to make real design decisions: how to represent a task, how to turn typed text into actions, where to keep the data, and how to report mistakes. In this lesson you build a command-line manager that understands commands such as add Buy milk, done 2 and list.

You will practice data classes, enum classes, sealed interfaces, collections, interfaces and reading input. If you did the calculator project, the "parse text into a typed value" step will feel familiar. The next project is the bank simulation.

The design

Four small pieces, each with one job:

TEXT
text line --parse()--> Command --TodoService--> changes the Repository --> text output
  • Task is an immutable data class.
  • Command is a sealed interface: one subtype for every action the user can ask for.
  • TaskRepository is an interface that stores tasks. We provide an in-memory version.
  • TodoService applies a command to the repository and returns a message.

Splitting the work this way means you can change one piece without touching the others. Want to store tasks in a file later? Write a new TaskRepository; nothing else changes.

Step 1: the task and the repository

A task has an id, a title, a priority and a done flag. We make it a data class with only val properties. To "change" a task you create a modified copy with copy(), which keeps the model safe against accidental edits (see data classes and encapsulation).

Kotlin Step 1 - tasks and an in-memory repository

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 choices worth noticing:

  • all() returns a copy (toList()), not the internal map. If we returned the live collection, callers could change our data behind our back.
  • The map is a linkedMapOf, so tasks keep their insertion order when printed. A plain HashMap would give no promise about order (see maps).
  • find returns Task?. "Not found" is a normal situation, so a nullable result is better than an exception (null safety).
  • update uses require, because passing an unknown id is a programmer mistake, not a user mistake (require, check and assert).
  • IDs are never reused. After remove(1), the next task gets id 4 and not 1. Reusing ids confuses users who remember "task 2".

Immutable data with copy() creates a new Task object on every change. For a to-do list that cost is nothing. For millions of updates per second you would think twice, but "correct first, optimize later" is the right order here.

Step 2: commands as a sealed type

The user types text. Our program should not scatter if (line.startsWith("add")) checks everywhere. Instead, one function turns a line into a Command value. After that, the rest of the program works with types.

Kotlin Step 2 - parse lines into commands

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.

Look at the output of data object values: they print as their plain name (see sealed classes and interfaces). The parsing function is the only place that knows the text syntax. If you later add a / prefix style or a different language, you change one function.

split(Regex("\\s+"), limit = 2) cuts the line into at most two parts: the command name and everything else. The limit matters. add Buy milk has to give the title Buy milk including the space, not just Buy.

Step 3: saving and loading as text

"Persistence" means that data survives a restart. Our sandbox has no permanent disk, but the design is the same as for a real file: turn the list of tasks into text, and turn the text back into tasks. We store one task per line with tab-separated fields. Tabs and line breaks inside titles would break that format, so we escape them.

Kotlin Step 3 - serialize and restore

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.

Two things protect us from a bad file. toBooleanStrict() accepts only true or false (not yes or TRUE), and Priority.valueOf throws on an unknown name. In a real application you would catch these and report "the save file is damaged". Equality of the restored list is a one-line check, because data classes compare by content.

For a real project, store data in JSON or a database rather than inventing a text format. This lesson uses a hand-made format to show the idea of escaping and round-tripping; compare it to working with JSON text.

Step 4: a compile error you will meet

Imagine that someone returns a List<Task> from the repository, and a caller tries to add to it directly. In Kotlin, List is read-only and has no add function. The mistake is caught at compile time.

Kotlin Changing a read-only list (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 error says that add is an unresolved reference for List<Task>. That is the very protection we wanted when all() returned a List. The fix is to go through the repository (repo.add(...)), which is the single place that controls how tasks are created.

Step 5: the service and the whole program

Now the service applies commands. A when over the sealed Command produces the message to show. Because it is an expression with no else, adding a new command later makes the compiler point at this function.

The program below reads a scripted session from stdin. Change the lines in the Input box to try your own commands.

Kotlin Step 5 - the finished to-do manager

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.

Walk through the printed session. Several things happen that are easy to miss:

  • continue inside the catch block jumps to the next input line. Because try is used as an expression, the compiler knows that after the catch there is no command to use, so continue (type Nothing) is fine (nothing, unit and any).
  • Removing task 3 a second time gives No task #3 and not a crash. A missing task is expected, so the service reports it as text.
  • done abc is rejected by the parser before the service even sees it.
  • The listing sorts open tasks first, then by priority (high first), then by id, using a comparator chain.
  • The last line, add never reached, is not executed because quit ends the loop.

Why Command.Quit -> ... without is

Quit is a data object, so it is a single value. In a when, you can compare against it directly. This is both shorter and clearer than is Command.Quit.

Improvements to try

  1. Real persistence. Write a FileTaskRepository that calls serialize after each change, using the code from Step 3 with files and IO. The service does not change.
  2. Due dates. Add a LocalDate? to Task and a due command. See dates and times.
  3. Undo. Keep a stack of previous repository states; since tasks are immutable, snapshots are cheap.
  4. Search and tags. find <text> with filter { text in it.title }.
  5. Tests. The parser and the service are pure functions of their input, so they are easy to test (see testing basics).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the repository's all() function return tasks.values.toList() instead of the internal collection?

    Returning a copy protects the invariants of the repository. Changes happen only through add, update and remove.
  2. 2. What does split(Regex("\\s+"), limit = 2) do for the line add Buy milk?

    With limit = 2 the string is cut at most once, so the title keeps its spaces.
  3. 3. Why is Command a sealed interface?

    A sealed hierarchy is closed, so an exhaustive when without else becomes a compile error when a command is forgotten.
  4. 4. Which approach fits an unknown task id typed by the user?

    A missing task is an expected situation for user input, so the service handles it with a message. require() is for programmer mistakes.
  5. 5. What is the benefit of putting tasks behind the TaskRepository interface?

    The service depends on the interface only. Another implementation can be plugged in later.

Summary

  • Model the data as immutable data classes and change it with copy().
  • Turn text into a typed Command once, at the edge of the program, and report mistakes with a dedicated exception.
  • A sealed command type plus a when expression makes the compiler guard the service.
  • Hide storage behind an interface; return copies, not internal collections.
  • Persistence is "serialize to text, parse back": escape special characters and validate strictly when loading.
  • Distinguish expected outcomes (unknown id: a message, nullable result) from programmer errors (require).

Next: Project: Bank Account Simulation