Sobes.tech
Junior — Middle

What is the difference between sealed classes and enum classes in Kotlin, and what are their main differences?

sobes.tech AI

Answer from AI

Sealed classes and enum classes in Kotlin serve to restrict class hierarchies but have different purposes and features:

  • Sealed classes allow limiting the set of subclasses that can inherit from a base class. All subclasses must be declared in the same file as the sealed class. This is convenient for creating restricted hierarchies with different data types.

  • Enum classes are intended to define a fixed set of constants (enumerations). Each enum element is an object of that class.

Main differences:

Characteristic Sealed class Enum class
Purpose Restrict inheritance Define a fixed set of constants
Subclasses Can be different classes Only enum constants
Subclass placement In the same file All elements listed inside enum
Ability to have state and behavior Yes, subclasses can have different properties and methods Yes, but all elements are instances of the same class

Example of a sealed class:

sealed class Result
class Success(val data: String) : Result()
class Error(val error: Throwable) : Result()

Example of enum:

enum class Direction {
    NORTH, SOUTH, EAST, WEST
}