Junior — Middle
What is the difference between a sealed class and an enum?
sobes.tech AI
Answer from AI
A sealed class and an enum are different concepts, although both restrict the set of possible options.
-
Sealed class — a class that restricts inheritance: all subclasses must be declared in the same file. This allows the compiler to know all possible subclasses and use this for safe pattern matching. Sealed classes are often used to model hierarchies with a limited number of options, where each option can have its own properties and behavior.
-
Enum — a set of named constants, typically used to represent a fixed set of values. In Android (Kotlin/Java), an enum is a type where each element is an object, but usually without complex logic.
Key differences:
- Enum — a fixed set of values without inheritance.
- Sealed class — a restricted class hierarchy with the ability to add complex behavior and properties.
Example in Kotlin:
sealed class Result {
data class Success(val data: String) : Result()
object Error : Result()
}
enum class Direction {
NORTH, SOUTH, EAST, WEST
}