Difference between Enum and Sealed Classes in Kotlin

Jesse Okoro
2 min readDec 13, 2020

--

Let’s look at the difference between them using one simple example. The class Rainbow , which contains different set of colors. It will be represented both in Enum and Sealed class.

enum class Rainbow (val color: String) {
RED (“Red”),
GREEN (“Green”),
BLUE (“Blue”),
ORANGE (“Orange”),
YELLOW (“Yellow”);
}

Each of the items in the Enum above is a separate instance of the Enum. You can use the values anywhere by passing by passing them to variables.

var color = Rainbow.RED.color

Methods can also be added Enum classes. When that happens, every instance of the class is associated with every method in the Enum. Enum also provides some in-built properties and methods in Kotlin like name is a property that allows you to get the name of the Enum's instance ordinal contains the position of an Enum instance

val color: Rainbow = Rainbow.GREEN
println(color.ordinal)

Output:

1

valueOf(), returns an instance of Enum by its name with String type. It is case sensitive:

println(Rainbow.valueOf("RED"))

Output:

RED

values() returns an array of all instances of Enum. It might be helpful if you want to iterate through Enum instances.

fun isRainbow(color: String) : Boolean {
for (enum in Rainbow.values()) {
if (color.toUpperCase() == enum.name) return true
}
return false
}

let’s try it out:

println(isRainbow("blue"))

this will return

true

Let’s look at the same example as a Sealed Class Let’s look at the same example as a Sealed Class

sealed class Rainbow(){
class Red(val color: String): Rainbow()
class Green(val color: String): Rainbow()
class Blue(val color: String): Rainbow()
class Orange(val color: String): Rainbow()
class Yellow(val color: String): Rainbow()
}

We create a sealed class called Rainbow, which contains five different colors: Red, Green, Blue, Orange and Yellow. The good thing about this is that now when expressions will require us to provide branches for all possible types:

fun execute(col: Rainbow) = when (color) {
is "Red" -> "Red"
is "Green" -> "Green"
is "Blue" -> "Blue"
is "Orange" -> "Orange"
is "Yellow" -> "Yellow"
}

when will complain if you leave any of the subclasses out. It won't comply.

IN CONCLUSION

While Enum represents a logical sets of constants and allows you create your own enumeration just from a usual class, a Sealed class allows you to represent constrained hierarchies in which an object can only be of one of the given types. A sealed class is more or less a sealed class with super powers. They are similar in nature; The difference between them is that in the enum we only have one object per type, while in the sealed classes we can have several objects of the same class.

--

--

Jesse Okoro
0 Followers

Software Engineering intern at Decagon Institute