Junior — Middle
What is the main difference between sealed classes and enums in a programming language?
sobes.tech AI
Answer from AI
The main difference between sealed classes and enums in programming languages (e.g., Kotlin) lies in their purpose and capabilities:
-
Enum is a set of fixed constants, each representing one of the possible values. Enums are suitable when you need to restrict a set of options and work with them as a single type.
-
Sealed class is an abstract class that restricts inheritance to a specific set of subclasses declared in the same file. This allows creating type hierarchies with different states and behaviors while maintaining control over extensibility.
Example:
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val error: Throwable) : Result()
}
enum class Direction {
NORTH, SOUTH, EAST, WEST
}
- Enum is a simple set of values without additional logic.
- Sealed class allows storing different data and methods in each subclass, which is convenient for modeling complex states.
Thus, sealed classes are more flexible and suitable for modeling complex variants with different logic, while enums are for simple fixed sets of values.