Sobes.tech
Middle

Tell about data classes and sealed classes in Kotlin.

sobes.tech AI

Answer from AI

Data classes in Kotlin are used for storing data. They automatically generate useful methods like equals(), hashCode(), toString(), copy(), as well as component functions for destructuring.

// Example of a data class
data class User(val name: String, val age: Int)

Sealed classes are used to represent restricted class hierarchies. All subclasses must be defined in the same file as the sealed class itself (this restriction was loosened in Kotlin 1.5+). This allows the compiler to ensure exhaustive when expressions.

// Example of a sealed class
sealed class Result {
    data class Success(val data: String) : Result()
    data class Error(val message: String) : Result()
    object Loading : Result()
}

// Example of using a sealed class in a when expression
fun processResult(result: Result) {
    when (result) {
        is Result.Success -> println("Success: ${result.data}")
        is Result.Error -> println("Error: ${result.message}")
        Result.Loading -> println("Loading...")
    }
}

Main differences:

  • Purpose: data classes are for data storage, sealed classes are for restricting class hierarchies.
  • Generated methods: data classes generate standard data methods, sealed classes do not.
  • Subclass restrictions: sealed classes impose restrictions on subclass declarations, data classes do not.
  • Exhaustive when: Kotlin compiler can check for exhaustive subclass handling in when without an else branch.

Both sealed and data classes can be abstract, but data classes cannot be open (since they are final by default) and cannot directly implement open methods (only through interfaces or abstract classes). Sealed classes are abstract by default, and their constructors are private.