Sobes.tech
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 when without an else.

  • data class is a class designed for storing data. It automatically generates methods like equals, hashCode, toString, as well as copy and componentN functions 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.

How does a sealed class declaration differ from a… - sobes.tech