Marking a class data tells the compiler to generate five things from the constructor properties: a sensible toString, a content-based equals, a matching hashCode, a copy function, and componentN functions for destructuring. This is the single biggest reduction in boilerplate Kotlin offers, and it is why domain models in Kotlin are usually one line each.
Content-based equality is the important one. Two data class instances with the same property values are equal, which means they behave correctly as map keys and in set membership tests without you writing anything. Getting equals and hashCode right by hand is notoriously error-prone, and generated versions cannot drift out of sync when a property is added.
copy produces a new instance with some properties changed. This is how you update immutable state - and it is exactly how state is updated in Jetpack Compose and in any architecture built on unidirectional data flow, which level five covers.
Only properties declared in the primary constructor take part. A property declared in the class body is excluded from equals, hashCode, toString and copy - which is occasionally what you want and more often a surprise, so it is worth knowing before it bites.
data class User(val id: Int, val name: String, val email: String)
fun main() {
val original = User(1, "Ada", "ada@example.com")
// Generated toString, no manual work
println(original) // User(id=1, name=Ada, email=ada@example.com)
// Content equality, not reference equality
val twin = User(1, "Ada", "ada@example.com")
println(original == twin) // true
println(original === twin) // false - different objects
// copy: the idiomatic way to change immutable state
val renamed = original.copy(name = "Ada Lovelace")
println(renamed)
// Destructuring, powered by the generated component functions
val (id, name, email) = renamed
println("$id / $name / $email")
}
Discussion
No questions on this topic yet. Sign in to ask the first one.