Sealed Class vs Sealed Interface vs Enum in Kotlin

Abhinay Gupta
6 min readMar 20, 2024
Source: Guide to using sealed classes in Kotlin — LogRocket Blog

All my articleas are available for free to read. Here’s the link to this one.

Why do we require sealed classes/interfaces?

In Kotlin, classes and interfaces serve not only as containers for operations or data but also facilitate the representation of hierarchies through polymorphism. For example, consider a scenario where you make a network request. The outcome of this request can either be successful, resulting in the receipt of the requested data, or it can fail, providing information about the encountered error. These two potential outcomes can be depicted using two classes that implement an interface or abstract class:

interface Result
class Success(val data: String) : Result
class Error(val message: String, val statusCode : Int) : Result
abstract class Result
class Success(val data: String) : Result()
class Error(val message: String, val statusCode : Int) : Result()

When function returns the Result object, we know it can either be Success or Error.

val result: Result = getSomeData()
when (result) {
is Success -> handleSuccess(result.data)
is Error -> handleError(result.message, result.statusCode)
}

--

--

Abhinay Gupta
Abhinay Gupta

Written by Abhinay Gupta

Exploring personal growth, tech, and culture through engaging storytelling | Inspiring and connecting with readers worldwide.

No responses yet