Explain it simply
Explain it simply
Over the next three lessons you will build a small Task Manager that you drive with text commands such as add, done and list. Part 1 builds only the foundation: what a task is, where tasks are kept, and what happens when someone gives bad input.
Picture a notice board in an office with a printed form for every job. Each form has a number printed in the corner, a title line and three boxes for priority. Staff can fill in a form, but nobody can change the number once it is printed, and only the office clerk holds the key to the board. In Kotlin the form is a data class, the three priority boxes are an enum, and the clerk with the key is the TaskRepository class. Every feature you add later goes through that clerk.
Problem → Why → Solution
The problem: a first draft that compiles and still breaks
Here is how most first drafts look. Task has var fields, priority is a plain String, the list is a loose variable, and the id comes from tasks.size + 1. Everything compiles and the first demo works, so it feels finished.
Then the trouble starts. One task is removed, a new one is added, and the new task receives an id that is already taken. The priority "hihg" is a typo, but a String accepts it, so any later filter for "high" silently skips that task. Nothing throws and nothing is printed; the program simply keeps wrong data.
data class Task(var id: Int, var title: String, var priority: String)
fun main() {
val tasks = mutableListOf<Task>()
tasks.add(Task(tasks.size + 1, "Write report", "high"))
// "hihg" is a typo, but a String accepts it
tasks.add(Task(tasks.size + 1, "Call Ko Aung", "hihg"))
tasks.removeAt(0)
// only one task is left, so size + 1 is 2 again
tasks.add(Task(tasks.size + 1, "Send invoice", "low"))
println(tasks.map { it.id }) // [2, 2]
}Why doesn't the compiler complain?
Every line follows Kotlin's rules. A String can hold any text, a var can be reassigned, a public list can be changed by anyone, and size + 1 is a perfectly valid Int. The compiler checks types, not intentions. To make these bugs impossible you have to say what you mean in the types: an enum for the closed choice, val for fields that must not change, and a class that owns the list and the id counter.
Core concept: write the rules down as types
A project like this goes wrong when its rules live only in the programmer's head. Part 1 writes those rules down as types and lets the compiler enforce what it can. There are four decisions, and each one removes one kind of bug.
1. Turn a closed choice into an enum
Priority has exactly three valid values, so enum class Priority { LOW, MEDIUM, HIGH } replaces the free-form String. A typo such as HIHG no longer compiles, Priority.entries gives you the full list when you need a menu or must parse user text later, and the entries are ordered (LOW comes before MEDIUM, which comes before HIGH), which Part 3 uses for sorting.
2. Turn a record into an immutable data class
data class Task generates toString(), equals(), hashCode() and copy() from the constructor properties. Declare every property with val: a task is a fact, and to change it you build a modified copy with copy(isDone = true). That also means an id can never be edited by accident, and a default value such as isDone = false lets callers leave that argument out.
3. Put the list behind a repository
TaskRepository owns a private mutable list and a private counter, so callers can only use add, findById and all. all() returns toList(), a snapshot, so nobody can clear the real list through the returned value. The counter nextId only ever grows, which keeps ids unique even after Part 2 starts removing tasks.
4. Reject bad input loudly, model absence with null
require(condition) { message } throws IllegalArgumentException the moment a caller breaks a rule, right at the entry point where the mistake is easy to find. A lookup that may legitimately find nothing is different: findById returns Task?, and the compiler forces every caller to decide what null means, usually with ?. or ?:.
| Situation | Kotlin tool | What you gain |
|---|---|---|
| A value must be one of a few options | enum class | Typos fail to compile |
| A caller broke a rule | require() throws | The mistake shows at the entry point |
| A lookup may find nothing | Return type Task? | The compiler forces null handling |
| A record must not change | val plus copy() | No accidental edits |
- Describe a task with a data class
- Close the choices with an enum
- Hide the list behind a repository
- Reject bad input at the entry point
Callers talk to the repository, and only the repository touches the list.
General pattern
enum class Level { FIRST, SECOND }
data class Item(val id: Int, val name: String, val level: Level)
class ItemStore {
private val items = mutableListOf<Item>()
private var counter = 1
fun add(name: String): Item { /* require(...), build, store, return */ }
fun find(id: Int): Item? = items.firstOrNull { it.id == id }
}Close the choices with an enum, describe one record with an immutable data class, then let one store class own the list and the id counter and expose only small functions.
Part 1 code: model, repository and a first run
The file below is the complete Part 1 program, and it runs as it is. Keep the names Priority, Task and TaskRepository in mind, because Part 2 and Part 3 reuse them unchanged and only add to them. The main function adds three tasks (one with extra spaces around its title), tries a blank title to show the rejection, prints every task with the free toString(), and finally looks up one id that exists and one that does not.
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 all(): List<Task> = tasks.toList()
}
fun main() {
val repo = TaskRepository()
repo.add("Review Kotlin syntax", Priority.HIGH)
repo.add(" Practice data classes ", Priority.MEDIUM)
repo.add("Read about null safety")
try {
repo.add(" ", Priority.LOW)
} catch (e: IllegalArgumentException) {
println("Rejected: ${e.message}")
}
repo.all().forEach { println(it) }
println("Task #2 -> ${repo.findById(2)?.title}")
println("Task #9 -> ${repo.findById(9)?.title ?: "not found"}")
}Code breakdown
- Closed choice
enum class Priority { LOW, MEDIUM, HIGH }Priority can only ever be one of three values. The compiler rejects Priority.URGENT, and the entries keep the order LOW, MEDIUM, HIGH.
- Immutable record with a default
val isDone: Boolean = false,Every property is a val, so a Task never changes after it is created. The default value means add() does not have to pass isDone, which is why every new task prints isDone=false.
- Unique ids that never shrink
val task = Task(id = nextId++, title = title.trim(), priority = priority)nextId++ uses the current value for this task and then increments the counter, so ids 1, 2 and 3 are each handed out once. trim() removes the extra spaces around the second title.
- Fail fast on bad input
require(title.isNotBlank()) { "Task title must not be blank" }isNotBlank() is false for an empty string and for a string of only spaces. When the condition is false, require throws IllegalArgumentException with the message in braces, which main catches and prints as Rejected.
- A lookup that may find nothing
fun findById(id: Int): Task? = tasks.firstOrNull { it.id == id }firstOrNull returns the first match or null, so the return type has to be Task?. main handles it with ?.title and the Elvis operator ?:, which is how id 9 prints not found.
- A read-only snapshot
fun all(): List<Task> = tasks.toList()toList() copies the elements into a new list. A caller who receives it can read it or even sort their copy, but cannot add or remove tasks in the repository.
Rejected: Task title must not be blank
Task(id=1, title=Review Kotlin syntax, priority=HIGH, isDone=false)
Task(id=2, title=Practice data classes, priority=MEDIUM, isDone=false)
Task(id=3, title=Read about null safety, priority=MEDIUM, isDone=false)
Task #2 -> Practice data classes
Task #9 -> not foundWhat a data class gives you for free
Writing data in front of class asks the compiler to generate the boring parts from the primary constructor. You get a readable toString(), equals() and hashCode() that compare property values, copy() for making a changed duplicate, and componentN() functions that power destructuring such as val (id, title) = task.
enum class Priority { LOW, MEDIUM, HIGH }
data class Task(
val id: Int,
val title: String,
val priority: Priority,
val isDone: Boolean = false,
)
fun main() {
val a = Task(1, "Write report", Priority.HIGH)
val b = Task(1, "Write report", Priority.HIGH)
println(a == b)
println(a === b)
val done = a.copy(isDone = true)
println(done)
println(a.isDone)
val (id, title) = a
println("$id / $title")
println(Priority.entries.map { it.name })
println(Priority.HIGH > Priority.LOW)
}The first == prints true because two separate objects with the same values are equal, while === checks identity and prints false. copy(isDone = true) leaves the original untouched, which is why a.isDone still prints false. The > comparison on enum entries works because entries compare by their declaration order.
Validating with require()
require belongs to a small family of precondition helpers in the standard library. Use require for arguments, the things the caller controls, and check for the object's own state; they throw IllegalArgumentException and IllegalStateException respectively, and both build their message lazily. The snippet also shows why isBlank() matters: a string of three spaces is not empty.
fun main() {
val title = " "
println(title.isEmpty())
println(title.isBlank())
try {
require(title.isNotBlank()) { "Task title must not be blank" }
} catch (e: IllegalArgumentException) {
println(e::class.simpleName + ": " + e.message)
}
}It prints false for isEmpty() because the string has three characters, true for isBlank(), and then the message from the exception that require throws. The message in braces only runs when the condition fails, so a helpful message costs nothing on the happy path.
Where the project goes next
Part 1 deliberately has no commands yet. Part 2 adds the features people actually use: completing a task, searching with lambdas, and a small command interpreter built on when. Part 3 finishes the job with a report interface, sorting and grouping, and saving tasks to a file. The three names you wrote today stay exactly the same.
Task Manager roadmap
--------------------
Part 1: model Part 2: features Part 3: polish
----------------- -------------------- ----------------------
Priority enum complete(), search() Reportable interface
Task data class TaskManager commands summary and sorting
TaskRepository lambdas, when, ?. save and load a fileIn real projects
In real projects
Almost every to-do list, ticketing system and order tracker starts from the same pieces: a record with an id, a few closed choices such as status or priority, and one place that stores and finds records. Teams usually call that place a repository. The rest of the program talks to its small interface, so the in-memory list used here can later be replaced by a database such as SQLite or PostgreSQL without touching the code that uses it.
The same shape appears at every boundary. A web endpoint turns a JSON body into a data class and runs require-style checks before storing anything, and a lookup that finds nothing becomes an HTTP 404 instead of a crash. The counter-based id used here is fine for one process that keeps everything in memory, but a real database hands out ids itself, through a sequence or a UUID, and shared code must never assume ids are consecutive.
Common mistakes
Common mistakes
Checking for blank with isEmpty()
isEmpty() only tests for length zero, so a title made of spaces passes the check and is stored as an invisible task. Use isBlank() or isNotBlank(), and store title.trim() so later comparisons and printed lists stay tidy.
Deriving ids from size + 1
As soon as a task can be removed, size + 1 hands out a number that is already taken, which is exactly the [2, 2] result in the draft above. Keep a separate counter that only increases, as nextId does here.
Returning the internal list
Writing fun all() = tasks makes the private list effectively public: the caller receives the real object, can call clear() on it after a cast, or simply keeps a reference that changes under its feet. Return tasks.toList() so every caller gets its own snapshot.
Best practices
Habits to keep for Parts 2 and 3
- Keep Priority, Task and TaskRepository named exactly as they are, because later parts extend them instead of replacing them.
- Run the program after every small change and compare the printed lines with what you predicted.
- Prefer val and read-only List in signatures, and use var and MutableList only inside the class that owns the data.
- When you add a rule, add one line to main that breaks it on purpose and confirm that it is rejected.
Mini challenge
Remove and rename without breaking ids
Extend TaskRepository with remove(id) and rename(id, newTitle), then prove two things in main: an id is never reused after a removal, and a blank new title is rejected.
- remove(id: Int): Boolean returns true only when a task was actually removed
- rename(id, newTitle) returns the updated Task, or null when the id does not exist, and rejects a blank title with require
- Replace the stored task with a copy that has the new title; do not turn title into a var
- main shows that after adding three tasks and removing #2, the next id is 4, not 3
// Reuse Priority and Task from the lesson: every Task property is a val.
class TaskRepository {
private val tasks = mutableListOf<Task>()
private var nextId = 1
fun add(title: String, priority: Priority = Priority.MEDIUM): Task {
// TODO: validate, build the task with nextId++, store it, return it
}
fun remove(id: Int): Boolean {
// TODO: true only if a task with this id was removed
}
fun rename(id: Int, newTitle: String): Task? {
// TODO: reject a blank title, then replace the stored task with a copy
// return the new task, or null when the id is unknown
}
fun all(): List<Task> = tasks.toList()
}
fun main() {
// TODO: add three tasks, remove #2 twice, add a fourth and print every id
// TODO: rename #1 with extra spaces, rename #99, rename #3 with a blank title
}Expected: remove #2 prints true and then false, the new task gets id 4, the ids are [1, 3, 4], the rename returns the trimmed title, renaming id 99 prints null, and the blank rename prints Task title must not be blank.
Show hint
tasks.removeAll { it.id == id } returns true when something was removed. For rename, find the position with indexOfFirst, build the changed task with copy(title = ...), and write it back with tasks[index] = renamed.
Show solution
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" }
return Task(nextId++, title.trim(), priority).also { tasks.add(it) }
}
fun remove(id: Int): Boolean = tasks.removeAll { it.id == id }
fun rename(id: Int, newTitle: String): Task? {
require(newTitle.isNotBlank()) { "Task title must not be blank" }
val index = tasks.indexOfFirst { it.id == id }
if (index == -1) return null
val renamed = tasks[index].copy(title = newTitle.trim())
tasks[index] = renamed
return renamed
}
fun all(): List<Task> = tasks.toList()
}
fun main() {
val repo = TaskRepository()
repo.add("Write report", Priority.HIGH)
repo.add("Call Ko Aung")
repo.add("Send invoice", Priority.LOW)
println("remove #2: ${repo.remove(2)}")
println("remove #2 again: ${repo.remove(2)}")
println("new task id: ${repo.add("Plan sprint").id}")
println("ids: ${repo.all().map { it.id }}")
println("rename #1: ${repo.rename(1, " Write final report ")?.title}")
println("rename #99: ${repo.rename(99, "Ghost")}")
try {
repo.rename(3, " ")
} catch (e: IllegalArgumentException) {
println("blank rename: ${e.message}")
}
println("titles: ${repo.all().map { it.title }}")
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Design the data first: an enum for closed choices and an immutable data class for each record
- Let one repository class own the mutable list and the id counter, and return toList() snapshots
- Use require() for bad input and a nullable return type for lookups that may find nothing
- isBlank() catches whitespace-only titles, and size + 1 is not a safe way to make ids
Kotlin language guide — Kotlin