Kotlin Data Classes
A data class is a class whose main job is holding data. Kotlin builds the printing and comparing work for a data class from its properties.
Printing a data object
This print needs no extra work inside the class. The output names each property and shows its value.
data class Student(val name: String, val score: Int)
fun main() {
val student = Student("Ana", 90)
println(student)
}Equal values compare as equal
Both objects hold the same name and the same score here. The print shows true because their values match.
data class Student(val name: String, val score: Int)
fun main() {
val first = Student("Ana", 90)
val second = Student("Ana", 90)
println(first == second)
}The same test on a plain class
This class has no data word in front of it. Both objects hold the same values and the print still shows false.
class Student(val name: String, val score: Int)
fun main() {
val first = Student("Ana", 90)
val second = Student("Ana", 90)
println(first == second)
}copy makes a changed twin
The copy call names the score property and gives it a new value. The first print shows the old object and the second print shows the twin.
data class Student(val name: String, val score: Int)
fun main() {
val ana = Student("Ana", 90)
val better = ana.copy(score = 95)
println(ana)
println(better)
}Example
data class Point(val x: Int, val y: Int)
fun main() {
val start = Point(2, 3)
val moved = start.copy(x = 5)
println(start)
println(moved)
println(start == Point(2, 3))
}Key points
- Write the word data before class to make a data class.
- Printing a data object shows each property name and its value.
- The sign == compares two data objects by their property values.
- Use copy to make a new object that shares most values with an old one.
- A property named at a copy call is the one value that changes in the twin.
In this example, start is a Point with x 2 and y 3. The copy call names x and makes a twin with x 5 and the same y. The prints show the first point and then the twin. The last print shows true because a fresh Point with the same values equals start.
Note
Two plain class objects count as equal only when they are the same object.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
What does copy do on a data object?