Adding tasks
- Kotlin course
- Beginner
- Lesson 84/116
- 6 min
Learn to add tasks with the addTask function.
Adding tasks: TodoList and addTask
Now we will set up a second class to store tasks: TodoList. This class keeps Task objects in a MutableList<Task> and adds new tasks with the addTask method.
class TodoList {
val tasks = mutableListOf<Task>()
fun addTask(title: String) {
tasks.add(Task(title))
}
}addTask creates a new Task and adds it to the list. The caller only provides the title; object creation stays hidden inside the method.
TodoList and Task together
The TodoList class stores Task objects in a list. addTask adds one element per call. To print the list you can use tasks.forEach { println(it.format()) }.
val list = TodoList()
list.addTask("Shopping")
list.addTask("Homework")
list.tasks.forEach { println(it.format()) }
// [ ] Shopping
// [ ] HomeworkIn the next step we will move this print into a listTasks method; that way the main code stays simple.
Practice Define TodoList and addTask
Define a class TodoList with val tasks = mutableListOf<Task>() and fun addTask(title: String) { tasks.add(Task(title)) }. In main create a TodoList, add two tasks, and print them with list.tasks.forEach { println(it.format()) }.
Starter code
fun main() {
val list = TodoList()
// Add two tasks with addTask and print their format outputs with forEach
}
// Define the Task data class: title (String), done (Boolean, default false)
// format function: "[x] title" if done, otherwise "[ ] title"Sample solution
fun main() {
val list = TodoList()
list.addTask("Shopping")
list.addTask("Homework")
list.tasks.forEach { println(it.format()) }
}
data class Task(val title: String, val done: Boolean = false) {
fun format() = if (done) "[x] $title" else "[ ] $title"
}
class TodoList {
val tasks = mutableListOf<Task>()
fun addTask(title: String) {
tasks.add(Task(title))
}
}Expected output
[ ] Shopping [ ] Homework
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: add a Task to the list
tasks.____(Task(title))
tasks.add(Task(title))
Explanation: tasks.add(Task(title)) appends the new task.
2 Match expression to role
| Term | Meaning |
|---|---|
MutableList<Task> |
Task list |
addTask(title) |
Adds a new task |
tasks.add(...) |
Appends to the list |
Task(title) |
New task object |
3 What should the return type of addTask be?
- Int (index)
- Boolean
- Task (the added one)
- Unit (only appends) Correct answer
Explanation: addTask returns nothing; it only appends. So it is Unit.