Skip to Content
Course content

71: Practice Exercise: Building a Class-Based To-Do List

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think about a physical corkboard in a home office. You have a stack of sticky notes and a board to pin them to. Each sticky note is its own little entity; it has a message written on it and maybe a check-mark in the corner once the task is done. The corkboard, however, isn't just a piece of foam—it's the system. It's where you decide where a note goes, which ones to rip off and throw away, and how to organize them so you don't lose your mind.

In Kotlin, we map this exactly: the sticky note is our TodoItem data class, and the corkboard is our TodoList management class. If you just used a list of strings, you'd be able to store the task name, but you'd have no clean way to track if it was completed without creating a second, parallel list (which is a recipe for bugs). By using a class, we bundle the "what" (the task) with the "state" (is it done?).

Defining the Blueprint for a Task

I always recommend starting with a data class for the items themselves. Since a To-Do item is primarily a container for data, the data class gives us equals() and toString() for free, which makes debugging a lot less painful when you're printing your list to the console.

data class TodoItem(
    val id: Int, 
    var description: String, 
    var isCompleted: Boolean = false
)

Notice I used var for the description and status. In a real app, tasks change—you might rename "Buy milk" to "Buy almond milk," or mark it complete. The id stays a val because the identity of the task shouldn't change once it's created.

Managing the Collection

Now we need the "corkboard." This is where the logic lives. I don't want the main part of my program worrying about how the list is stored; I just want to tell the manager to "add a task" or "complete task #5."

class TodoList {
    private val items = mutableListOf<TodoItem>()
    private var nextId = 1

    fun addTask(description: String) {
        items.add(TodoItem(nextId++, description))
    }

    fun completeTask(id: Int) {
        items.find { it.id == id }?.let {
            it.isCompleted = true
        }
    }

    fun removeTask(id: Int) {
        items.removeIf { it.id == id }
    }

    fun showAll() {
        if (items.isEmpty()) {
            println("Your list is empty!")
            return
        }
        items.forEach { println("${it.id}: [${if (it.isCompleted) "X" else " "}] ${it.description}") }
    }
}

A quick tip: I made the items list private. This is a crucial habit. If you make it public, any other part of your code can reach in and clear the whole list or add nulls without going through your addTask logic. Keep your data guarded.

Putting the Logic to Work

When you actually run this, you're just interacting with the manager. You don't touch the TodoItem objects directly from your main function; you let the TodoList class handle the orchestration. This separation is what makes your code maintainable as it grows.

fun main() {
    val myTasks = TodoList()
    
    myTasks.addTask("Finish Kotlin course")
    myTasks.addTask("Clean the kitchen")
    myTasks.addTask("Call the bank")
    
    myTasks.completeTask(1) // Marking the first task done
    myTasks.removeTask(2)   // Decided I don't care about the kitchen
    
    myTasks.showAll()
}



📋 Practical Task

The Priority-Based Task Manager Expansion

Your task is to take the basic To-Do list implementation and add a layer of importance to it. In the real world, not all tasks are created equal.

  • Update the Data Class: Add a Priority enum (with values LOW, MEDIUM, HIGH) to the TodoItem class.
  • Modify the Manager: Update the addTask function in the TodoList class to accept a priority level as an argument.
  • Add a Filter: Create a new function in the TodoList class called showHighPriorityTasks() that only prints tasks marked as HIGH.
  • Test it: In your main function, add three tasks with different priorities, mark one as complete, and then call your new filter function to ensure only the high-priority items appear.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.