What is the difference between enum and sealed in Kotlin?


What is the difference between enum (Enum Classes) and sealed (Sealed Classes). And when it is advisable to use them.

enum class Direction {

sealed class Direction {
    class NORTH
    class SOUTH
    class WEST
    class EAST
asked by lobito 24.09.2018 в 22:41

1 answer


Sealed Classes are used to represent hierarchies of restricted classes, when a value You can have one of the types of a limited set, but you can not have any other type.

The Sealed Classes are, in a sense, an extension of the enum classes : the set of values for an enum type is also restricted, but each enum constant exists only as a single instance, while a subclass of a sealed class can have multiple instances that can contain state.

  • In an enumeration, you can only have one object for each type.
  • In a sealed class you can have several objects of the same class.

I present these examples to you to see the difference, in when to your question, when is it advisable to use them?

actually the Sealed Classes could be said to be an "Enum with steroids" "

Enum :

enum class Direction {

Sealed Class : A class with a specific number of subclasses

sealed class Direction{
    class North(val value: Int) : Direction()
    class South(val value: Int) : Direction()
    class West(val value: Int) : Direction()
    class East(val value: Int) : Direction()


fun execute(direction: Direction)= when (direction) {
    is Direction.North -> direction.value + 0
    is Direction.East ->  direction.value + 90
    is Direction.South ->  direction.value + 180
    is Direction.West ->  direction.value + 270
answered by 24.09.2018 / 23:06