Data classes are one of Kotlin's coolest features. They're classes made specifically to hold data, and Kotlin auto-generates a bunch of useful methods for you. Less boilerplate, more productivity.
The data class magic
Just slap data before class and Kotlin handles the rest.
data class User(val name: String, val age: Int)
fun main() {
val user1 = User("Alice", 25)
val user2 = User("Alice", 25)
println(user1)
println(user1 == user2)
}
toString() gives you a readable string. equals() compares by property values, not object identity. Without writing a single line of that logic.
Auto-generated methods
Here's what you get for free: toString(), equals(), hashCode(), copy(), and componentN() functions.
data class Book(val title: String, val author: String, val year: Int)
fun main() {
val book = Book("1984", "George Orwell", 1949)
val newerEdition = book.copy(year = 2024)
println(book)
println(newerEdition)
val (title, author, year) = book
println("$title by $author ($year)")
}
copy() creates a new object with some properties changed. Destructuring with componentN() lets you unpack properties into variables in one go.
Rules for data classes
- The primary constructor must have at least one parameter
- All primary constructor parameters must be
valorvar - Data classes can't be
abstract,open,sealed, orinner
Stick to these rules and the Kotlin compiler does all the heavy lifting for you.