Middle
What are the differences between data classes and sealed classes in Kotlin?
sobes.tech AI
Answer from AI
Data classes in Kotlin are designed for storing data. They automatically generate useful methods like equals(), hashCode(), toString(), copy(), and componentN().
Sealed classes are used to represent a restricted class hierarchy. All subclasses of a sealed class must be declared in the same file. This allows the compiler to check all possible subtypes when using when expressions, ensuring exhaustiveness.
Main differences:
| Attribute | Data class | Sealed class |
|---|---|---|
| Purpose | Data storage | Restricted class hierarchy |
| Methods | Auto-generated | Not auto-generated |
| Subclasses | Can be anywhere | Restricted to same file |
| Usage | Like POJO (Plain Old Java Object) | To represent finite states |
| Abstract | Cannot be abstract |
Can be abstract |
Example of data class:
// Data class
data class User(val name: String, val age: Int)
Example of sealed class:
// Sealed class
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val code: Int, val message: String) : Result()
object Loading : Result() // Singleton object
}