0Pricing
Android Academy · Lesson

Data Classes & Sealed Classes

Use data classes for value-based equality and copy(), and sealed classes for exhaustive type hierarchies and clean state modeling.

What Are Data Classes?

A data class in Kotlin is a class whose primary purpose is to hold data. The compiler automatically generates useful methods for you:

  • equals() — compare two instances by value
  • hashCode() — consistent hash based on properties
  • toString() — readable string representation
  • copy() — create a modified copy
  • Destructuring support

Declaring a Data Class

Add the data keyword before class. All properties must be in the primary constructor:

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

fun main() {
    val u1 = User(1, "Alice", "alice@example.com")
    val u2 = User(1, "Alice", "alice@example.com")

    println(u1)          // User(id=1, name=Alice, email=alice@example.com)
    println(u1 == u2)    // true  (value equality)
    println(u1 === u2)   // false (different objects)
}

All lessons in this course

  1. Null Safety
  2. Classes & Objects
  3. Data Classes & Sealed Classes
  4. Extension Functions & Higher-Order Functions
← Back to Android Academy