Data Classes & Sealed Classes
Use data classes for value-based equality and copy(), and sealed classes for exhaustive type hierarchies and clean state modeling.
What Are Data Classes?
A data class in Kotlin is a class whose primary purpose is to hold data. The compiler automatically generates useful methods for you:
equals()— compare two instances by valuehashCode()— consistent hash based on propertiestoString()— readable string representationcopy()— create a modified copy- Destructuring support
Declaring a Data Class
Add the data keyword before class. All properties must be in the primary constructor:
data class User(val id: Int, val name: String, val email: String)
fun main() {
val u1 = User(1, "Alice", "alice@example.com")
val u2 = User(1, "Alice", "alice@example.com")
println(u1) // User(id=1, name=Alice, email=alice@example.com)
println(u1 == u2) // true (value equality)
println(u1 === u2) // false (different objects)
}All lessons in this course
- Null Safety
- Classes & Objects
- Data Classes & Sealed Classes
- Extension Functions & Higher-Order Functions