Data Classes in Kotlin

From the Kotlin cheat sheet · Data Classes & Objects · verified Jul 2026

Data Classes

Classes for holding data

kotlin
// Data class
data class User(
    val id: Int,
    val name: String,
    var email: String
)

val user = User(1, "Alice", "alice@example.com")
val copy = user.copy(email = "newemail@example.com")

// Destructuring
val (id, name, email) = user

// Generated methods
println(user.toString())  // User(id=1, name=Alice, email=alice@example.com)
println(user.hashCode())
println(user == copy)  // false (different email)

// Data class requirements
// - Primary constructor with at least one parameter
// - All parameters marked as val or var
// - Cannot be abstract, open, sealed, or inner
💡 Data classes auto-generate equals(), hashCode(), toString(), copy()
⚡ Destructuring declarations use componentN() functions
📌 Only properties in primary constructor are used in generated methods
🟢 Use copy() to create modified instances immutably

More Kotlin tasks

Back to the full Kotlin cheat sheet