kotlinbeginner

Data Classes — Copy, Destructure, and Equals

Use data classes for immutable models: auto-generated equals, hashCode, copy, and destructuring.

kotlin
data class User(
    val name: String,
    val email: String,
    val age: Int = 0,
    val roles: List<String> = emptyList()
)

data class Point(val x: Double, val y: Double) {
    fun distanceTo(other: Point): Double {
        val dx = x - other.x
        val dy = y - other.y
        return kotlin.math.sqrt(dx * dx + dy * dy)
    }

    operator fun plus(other: Point) = Point(x + other.x, y + other.y)
    operator fun times(factor: Double) = Point(x * factor, y * factor)
}

data class Range(val min: Int, val max: Int) {
    init {
        require(min <= max) { "min ($min) must be <= max ($max)" }
    }
    fun contains(value: Int) = value in min..max
}

fun main() {
    // Creation
    val user = User("Alice", "alice@test.com", 30, listOf("admin"))

    // Auto-generated toString
    println(user) // User(name=Alice, email=alice@test.com, age=30, roles=[admin])

    // Copy with modifications
    val updated = user.copy(age = 31, roles = user.roles + "editor")
    println(updated)

    // Structural equality (auto equals/hashCode)
    val user2 = User("Alice", "alice@test.com", 30, listOf("admin"))
    println(user == user2)  // true (structural)
    println(user === user2) // false (referential)

    // Destructuring
    val (name, email, age) = user
    println("$name ($email), age $age")

    // In collections
    val users = listOf(
        User("Alice", "a@t.com", 30),
        User("Bob", "b@t.com", 25),
        User("Alice", "a@t.com", 30) // duplicate
    )
    println("Distinct: ${users.distinct().size}") // 2

    // Map keys (hashCode is auto-generated)
    val scores = mapOf(user to 100, updated to 95)
    println("Score: ${scores[user]}") // 100

    // Destructuring in lambdas
    users.forEach { (name, email) ->
        println("$name: $email")
    }

    // Point with operators
    val p1 = Point(1.0, 2.0)
    val p2 = Point(4.0, 6.0)
    println("Distance: ${p1.distanceTo(p2)}")
    println("Sum: ${p1 + p2}")
    println("Scaled: ${p1 * 3.0}")
}

Use Cases

  • Immutable domain models and DTOs
  • Value objects with structural equality
  • Functional data transformations with copy

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.