Kotlin Data Classes

A data class is a class designed specifically to hold data. Kotlin generates common utility methods automatically — you write one line and get equality checks, a readable string representation, a copy function, and destructuring for free.

Defining a Data Class

data class Product(val name: String, val price: Double, val stock: Int)

This single line gives you a full-featured class. Compare that with Java, which would require 30–40 lines to achieve the same thing.

What Kotlin Generates Automatically


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

Auto-generated:
  ┌──────────────┬────────────────────────────────────────┐
  │ Method       │ What it does                           │
  ├──────────────┼────────────────────────────────────────┤
  │ toString()   │ "Point(x=3, y=7)"                      │
  │ equals()     │ true if x and y are equal              │
  │ hashCode()   │ consistent hash for use in sets/maps   │
  │ copy()       │creates a new copy with optional changes│
  │ componentN() │ enables destructuring                  │
  └──────────────┴────────────────────────────────────────┘

toString

data class User(val name: String, val age: Int, val email: String)

val u = User("Alice", 30, "alice@mail.com")
println(u)
// User(name=Alice, age=30, email=alice@mail.com)

equals and hashCode

val p1 = User("Alice", 30, "alice@mail.com")
val p2 = User("Alice", 30, "alice@mail.com")
val p3 = User("Bob", 25, "bob@mail.com")

println(p1 == p2)   // true  (same content)
println(p1 == p3)   // false (different content)
println(p1 === p2)  // false (different objects in memory)

copy

val original = User("Alice", 30, "alice@mail.com")

val updated = original.copy(age = 31)
println(original)  // User(name=Alice, age=30, email=alice@mail.com)
println(updated)   // User(name=Alice, age=31, email=alice@mail.com)

val renamed = original.copy(name = "Alicia", email = "alicia@mail.com")
println(renamed)   // User(name=Alicia, age=30, email=alicia@mail.com)

Destructuring

data class Point(val x: Int, val y: Int)
data class Order(val id: Int, val item: String, val total: Double)

val point = Point(10, 25)
val (x, y) = point
println("x=$x, y=$y")   // x=10, y=25

val order = Order(1001, "Laptop", 75000.0)
val (id, item, total) = order
println("Order $id: $item for ₹$total")

// Destructuring in a loop
val orders = listOf(Order(1, "Pen", 10.0), Order(2, "Book", 120.0))
for ((id, item, total) in orders) {
    println("$id → $item → ₹$total")
}

Data Class Rules


✓ Must have at least one parameter in the primary constructor
✓ All parameters should be val or var
✗ Cannot be abstract, open, sealed, or inner (in most cases)
✓ Can have extra functions and properties defined in the body

Practical Example: Student Records

data class Student(
    val id: Int,
    val name: String,
    val score: Double,
    val passed: Boolean = score >= 50.0
)

fun main() {
    val students = listOf(
        Student(101, "Priya", 88.5),
        Student(102, "Raj", 45.0),
        Student(103, "Meena", 72.0),
        Student(104, "Arjun", 38.0),
        Student(105, "Sunita", 91.5)
    )

    println("=== All Students ===")
    students.forEach { println(it) }

    println("\n=== Passed ===")
    students.filter { it.passed }.forEach { println("${it.name}: ${it.score}") }

    val topStudent = students.maxByOrNull { it.score }!!
    val promoted = topStudent.copy(score = topStudent.score + 5.0)
    println("\nTop student before promotion: $topStudent")
    println("After bonus points: $promoted")
}

Leave a Comment

Your email address will not be published. Required fields are marked *