Data Classes
Adding the data keyword before class generates a readable toString(), a structural equals()/hashCode() pair (comparing by field values, not object identity), and a copy() method for creating a modified clone — all automatically, from the primary constructor's properties alone.
data class Point(val x: Int, val y: Int)
fun main() {
val p1 = Point(1, 2)
val p2 = Point(1, 2)
println(p1)
println(p1 == p2)
val p3 = p1.copy(y = 10)
println(p3)
}Point(x=1, y=2) true Point(x=1, y=10)
p1 == p2 is true even though they're two separate objects — a data class's == compares field values, unlike a plain class, where == would compare identity. p1.copy(y = 10) creates an entirely new Point with x copied from p1 and y overridden, leaving p1 itself untouched.
This site's Java course runs on OpenJDK 13 — records, Java's closest equivalent to this, didn't arrive until Java 16, so this is something Kotlin has that Java on this site genuinely doesn't.
Next: inheritance — and why, in Kotlin, you have to opt in to a class being inheritable at all.
Practice exercise
Define a data class Person with properties name (String) and age (Int). Create a Person named "Alice" aged 30, then print it directly.