Task model
- Kotlin course
- Beginner
- Lesson 83/116
- 6 min
Design the Task data class and list structure.
Task model: data class Task
In this project you will build a to-do app step by step. The first step is to define data class Task that represents a task.
data class Task(val title: String, val done: Boolean = false) {
fun format() = if (done) "[x] $title" else "[ ] $title"
}Each task has a title (title) and a completion state (done). done starts as false. The format function yields [x] title when done, otherwise [ ] title.
data class and equals
The biggest advantage of a data class is that equals is content-based: two Tasks are equal if their fields match. This makes search and indexOf on a list content-based.
val a = Task("Shopping")
val b = Task("Shopping")
a == b // true
a.equals(b) // trueThis makes it easy for completeTask later to find a task with indexOfFirst.
Practice Define the Task data class and print it
Define a data class Task(val title: String, val done: Boolean = false) with a body containing fun format() = if (done) "[x] $title" else "[ ] $title". In main create val t = Task("Shopping") and print it with println(t.format()).
Starter code
fun main() {
// Create a Task and print its format output
}
// Define the Task data class: title (String), done (Boolean, default false)
// format function: "[x] title" if done, otherwise "[ ] title"Sample solution
fun main() {
val t = Task("Shopping")
println(t.format())
}
data class Task(val title: String, val done: Boolean = false) {
fun format() = if (done) "[x] $title" else "[ ] $title"
}Expected output
[ ] Shopping
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a data class generate automatically?
- Only equals is generated
- Only toString is generated
- toString, equals, hashCode, copy are generated Correct answer
- Nothing is generated
Explanation: A data class auto-generates toString, equals, hashCode and copy.
2 Fill in the blank: data class
____ class Task(val title: String, val done: Boolean = false)
data class Task(val title: String, val done: Boolean = false)
Explanation: data class Task defines a data class.
3 Match class part to role
| Term | Meaning |
|---|---|
data class Task |
Data class |
val title |
Immutable title |
val done |
Immutable completion |
format() |
Readable output |