Classes
- Kotlin course
- Beginner
- Lesson 113/116
- 6 min
Set up the data model with class and constructor.
The TaskList class and mutableListOf
To manage multiple tasks you write a TaskList class. It contains a mutableListOf<Task>() and an addTask method that adds a new task.
class TaskList {
val tasks = mutableListOf<Task>()
fun addTask(title: String) {
tasks.add(Task(title))
}
}addTask takes a title, creates a new Task and adds it to the list. mutableListOf gives a mutable list; add appends a new element. This makes adding a task a one-liner.
Print the list
println(list.tasks) prints the whole list. The list's toString separates items with commas and wraps them in square brackets. Each Task's own toString is called.
list.addTask("Study Kotlin")
list.addTask("Shopping")
println(list.tasks)
// [[ ] Study Kotlin, [ ] Shopping]This lets you see the list contents without writing a separate loop. Notice how the toString design in the Task class pays off here. A good toString makes debugging easier.
Practice Add two tasks and print them
Add a fun addTask(title: String) method to the TaskList class: create a new Task and add it to the tasks list. In main call list.addTask("Study Kotlin") and list.addTask("Shopping"), then print list.tasks with println.
Starter code
class Task(val title: String) {
var done: Boolean = false
override fun toString(): String {
return if (done) "[x] $title" else "[ ] $title"
}
}
fun main() {
val list = TaskList()
// Add two tasks and print the list
}
class TaskList {
val tasks = mutableListOf<Task>()
// addTask metodunu yaz: yeni Task yarat ve tasks'a ekle
}Sample solution
class Task(val title: String) {
var done: Boolean = false
override fun toString(): String {
return if (done) "[x] $title" else "[ ] $title"
}
}
class TaskList {
val tasks = mutableListOf<Task>()
fun addTask(title: String) {
tasks.add(Task(title))
}
}
fun main() {
val list = TaskList()
list.addTask("Study Kotlin")
list.addTask("Shopping")
println(list.tasks)
}Expected output
[[ ] Kotlin çalış, [ ] Alışveriş]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match concept to purpose
| Term | Meaning |
|---|---|
mutableListOf<Task> |
Task list |
addTask(String) |
Add task |
new Task |
Create object |
tasks.add |
Put in list |
2 What does addTask("Study Kotlin") do?
- Removes a task from the list
- Prints the list
- Completes the task
- Creates a new Task and adds it to the list Correct answer
Explanation: addTask creates a new Task object and adds it to the list.
3 Fill in the blank: call addTask
val list = TaskList()
list.____("Study Kotlin")
val list = TaskList()
list.addTask("Study Kotlin")
Explanation: addTask takes a title and adds a new task to the list.