Junior — Middle
How does a sealed class declaration differ from a data class in Kotlin?
sobes.tech AI
Answer from AI
sealed class and data class in Kotlin serve different purposes:
-
sealed class is a restricted class that can have a fixed set of subclasses. It is useful for modeling hierarchies with a limited number of options, such as representing states or events. The compiler knows all subclasses of a sealed class, which allows using
whenwithout anelse. -
data class is a class designed for storing data. It automatically generates methods like
equals,hashCode,toString, as well ascopyandcomponentNfunctions for convenient data handling.
Example of a sealed class:
sealed class Result {
data class Success(val data: String) : Result()
object Loading : Result()
data class Error(val error: Throwable) : Result()
}
Example of a data class:
data class User(val name: String, val age: Int)
Thus, a sealed class restricts the inheritance hierarchy, while a data class simplifies working with data.