How does the use of sealed class differ from enum regarding their constructors and ability to create instances?
sobes.tech AI
Answer from AI
An enum in Kotlin (and Java) represents a set of fixed constants. Each enum has a limited set of instances defined within the declaration. Enum constructors are always private, and new instances cannot be created — only those declared.
A sealed class is an abstract class with a limited set of subclasses, which are declared in the same file. Unlike enums, sealed classes allow creating different types with various structures and states. Sealed class constructors can be open or closed, and new instances of subclasses can be created, not just fixed constants.
Example:
// Enum with a private constructor and fixed instances
enum class Direction(val degrees: Int) {
NORTH(0), EAST(90), SOUTH(180), WEST(270)
}
// Sealed class with different subclasses and constructors
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val error: Throwable) : Result()
}
val res: Result = Result.Success("OK")
Thus, enum is limited to a fixed set of instances with a private constructor, while sealed class is more flexible, allowing the creation of different subclasses with their own constructors and states.