Sealed Class vs Sealed Interface vs Enum in Kotlin
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)
}
The issue arises when employing a standard interface or abstract class, as there is no assurance that all defined subclasses necessarily qualify as subtypes of this interface or…