Kotlin — Sealed Class

Destan Erik
Ekmob Developer Studio
2 min readMar 22, 2020
A sailboat in the ocean at the sunset.
Photo by Josh Sorenson on Unsplash

In this article, I will briefly explain what I understand Sealed Classes in Kotlin.

What is Sealed Class?

Accourding to official Kotlin Docs, they are, in a sense, an extension of Enum Classes. Basically, Enum Classes are named lists of constants. A typical Enum Class can be written in Kotlin as below.

enum class States{
SUCCESS, ERROR
}

In Kotlin, Each Enum constant is an object of the enum class. We can also re-write Statesby using Sealed Class.To create a Sealed Class, sealed modifier is used. For example,

sealed class States{
object SUCCESS: States()
object ERROR: States()
}

So…

Sealed Classes are another way to represent a concrete group of objects.But the main difference between them is that Sealed Classes allow you also to define constants using classes instead of objects so they can have more than one instance and therefore store an actual state. Let’s see the sample below.

sealed class ResponseStates{data class Success(val data: ResponseData) : ResponseStates()
object Error : ResponseStates()
}fun callApi(): ResponseStates{

return if (apiCall.isSuccessful)
Success(apiCall.data)
else
Error
}
...
fun setUI(){ var states = callApi() when(states)){
Success -> setData(states.data)
Error -> showError()
}
}

Important things to know about these classes…

— Sealed classes cannot be instantiated directly.

— Sealed classes cannot have public constructors. The constructors are private by default.

— Sealed classes are abstract and can have abstract members.

— Sealed classes can have subclasses, but they must either be in the same file or nested inside of the sealed class declaration.

End of Fun :)

--

--