Sobes.tech
Middle

What are data classes and sealed classes used for in Kotlin?

sobes.tech AI

Answer from AI

Data classes simplify the creation of classes intended solely for storing data. The compiler automatically generates for them:

  • equals()
  • hashCode()
  • toString()
  • copy()
  • componentN() for destructuring
data class User(val name: String, val age: Int)

// Usage
val user = User("Alice", 30)
println(user) // Outputs User(name=Alice, age=30)
val user2 = user.copy(age = 31)
val (name, age) = user // Destructuring

Sealed classes represent a restricted class hierarchy where all possible subclasses are known at compile time. This allows their use in when expressions without an else block, guaranteeing exhaustive checking of all possible cases.

sealed class Result {
    data class Success(val data: String) : Result()
    data class Error(val message: String) : Result()
    object Loading : Result() // Object, as it has no parameters
}

fun handleResult(result: Result) {
    when (result) {
        is Result.Success -> println("Success: ${result.data}")
        is Result.Error -> println("Error: ${result.message}")
        Result.Loading -> println("Loading...")
    }
}

Comparison:

Attribute Data class Sealed class
Purpose Data storage Restricted class hierarchy
Capabilities Automatic method generation Exhaustive when checks
Subclasses No specific restriction Must be defined in the same file or module
Usage Data models, DTOs State, event, variant representation