Listing tasks
- Kotlin course
- Beginner
- Lesson 85/116
- 6 min
Learn to print tasks formatted with listTasks.
Listing tasks: the listTasks method
Now we will add a listTasks method to TodoList that prints the tasks in a readable form. This method walks tasks with forEach and prints each task's format() output.
fun listTasks() {
tasks.forEach { println(it.format()) }
}Thanks to this method the main code stays simple: list.listTasks() writes all tasks in one line. Inside the forEach lambda each element is known as it.
it and forEach
Inside the forEach lambda the single parameter is automatically named it. In tasks.forEach { println(it.format()) }, it is the current Task; it.format() gives its readable output.
tasks.forEach { task ->
println(task.format())
}You can also give an explicit name: { task -> ... }. In nested lambdas where it is ambiguous, an explicit name improves readability.
Practice Add and call the listTasks method
Add a fun listTasks() { tasks.forEach { println(it.format()) } } method to TodoList. In main create a TodoList, add two tasks, and print them with list.listTasks().
Starter code
fun main() {
val list = TodoList()
list.addTask("Shopping")
list.addTask("Homework")
// Call the listTasks method from main
}
// The Task and TodoList classes stay as defined in the previous lesson.
// Add the listTasks method inside TodoList: use forEach to print format output.Sample solution
fun main() {
val list = TodoList()
list.addTask("Shopping")
list.addTask("Homework")
list.listTasks()
}
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))
}
fun listTasks() {
tasks.forEach { println(it.format()) }
}
}Expected output
[ ] Shopping [ ] Homework
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What should the return type of listTasks be?
- Unit (only prints) Correct answer
- List<Task>
- Int (count)
- String
Explanation: listTasks only prints; it returns no value, so it is Unit.
2 Match expression to role
| Term | Meaning |
|---|---|
listTasks() |
Prints all tasks |
forEach { } |
Walks each task |
it.format() |
Task's output |
println(...) |
Writes to screen |
3 Fill in the blank: walk each task
tasks.____ { println(it.format()) }
tasks.forEach { println(it.format()) }
Explanation: tasks.forEach { } walks each task.