← All courses

Data Classes, Enums & Sealed Classes

🗓 May 31, 2026 ⏱ 2 min read

Data classes

Most apps have classes whose only job is to hold data — a User, a Product, an ApiResponse. For these, mark the class data and Kotlin generates the tedious methods for you.

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

val u = User(1, "Anand", "a@x.com")
println(u)                       // User(id=1, name=Anand, email=a@x.com)  (toString)

val u2 = u.copy(name = "Gaur")   // make a modified copy
println(u == User(1, "Anand", "a@x.com"))  // true  (value equality)

val (id, name) = u               // destructuring

You get toString(), equals(), hashCode(), copy() and destructuring — all for free. This is perfect for models.

Enums: a fixed set of values

When something can only be one of a few known options (a direction, a status), use an enum.

enum class Status { LOADING, SUCCESS, ERROR }

enum class Planet(val gravity: Double) {
    EARTH(9.8), MARS(3.7);
    fun weight(mass: Double) = mass * gravity
}

val s = Status.SUCCESS
when (s) {
    Status.LOADING -> showSpinner()
    Status.SUCCESS -> showData()
    Status.ERROR   -> showError()
}

Sealed classes: enums with data

A sealed class is like an enum, but each case can carry its own data and all cases are known to the compiler. This is the ideal way to model UI state.

sealed class Result {
    data class Success(val data: List<User>) : Result()
    data class Error(val message: String) : Result()
    object Loading : Result()
}

fun render(result: Result) = when (result) {
    is Result.Success -> show(result.data)       // data available here
    is Result.Error   -> showError(result.message)
    Result.Loading    -> showSpinner()
    // no 'else' needed — compiler knows every case is covered
}

Because the compiler knows all subclasses, it forces you to handle every case — add a new state later and it tells you exactly where to update.

When to use which

  • data class — plain data holders (models).
  • enum — a fixed set of simple, value-less options.
  • sealed class — a fixed set of options where each carries different data (states, results).
Summary: Use data class for models, enum for simple fixed choices, and sealed class for states that carry data — the exhaustive when keeps your code safe as it grows.