Skip to content
Data Classes
step 1/6

Reading — step 1 of 6

Learn

~1 min readModern Type System

A data class is Kotlin's record type — auto-generates equals, hashCode, toString, copy, and destructuring components.

data class Point(val x: Int, val y: Int)

val p1 = Point(3, 4)
val p2 = Point(3, 4)
println(p1 == p2)        // true (structural equality)
println(p1)              // Point(x=3, y=4)

val p3 = p1.copy(x = 10)  // Point(x=10, y=4)
val (a, b) = p1           // destructuring: a=3, b=4

Replaces a lot of Java boilerplate. Used heavily for DTOs, immutable models, and pattern matching with sealed classes.

Default values make constructors flexible without overloading:

data class User(val name: String, val age: Int = 0, val active: Boolean = true)

User("Ada")                       // age=0, active=true
User("Ada", age = 36)             // named arg
User("Ada", active = false)

copy for updates — idiomatic immutable update:

val updated = user.copy(active = false, age = user.age + 1)

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…