Kotlin

Data Classes — Records Done Right

admin by @admin ADMIN
7m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`data class` auto-generates `equals`, `hashCode`, `toString`, `copy`, and `componentN` (destructuring). Replaces boilerplate POJOs / Records / classes-with-lombok in one line.
Kotlin
Raw
data class User(val id: Int, val name: String, val email: String)

fun main() {
    val alice = User(42, "Alice", "a@x.com")

    // toString included
    println(alice)        // User(id=42, name=Alice, email=a@x.com)

    // equals + hashCode based on all primary-constructor properties
    val alice2 = User(42, "Alice", "a@x.com")
    println(alice == alice2)    // true   (structural equality)
    println(alice === alice2)   // false  (different objects in memory)

    // copy — clone with overrides
    val renamed = alice.copy(name = "Alyce")
    println(renamed)

    // Destructuring via componentN()
    val (id, name, email) = alice
    println("$id $name $email")

    // Useful in maps as keys (because hashCode is consistent)
    val byUser = mapOf(alice to "admin")
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.