Introduction to Sealed Classes and Interfaces
Discover the use of sealed classes and interfaces for precise class hierarchies and code organization.
We'll cover the following...
The Result
interface and abstract class
Classes and interfaces in Kotlin are not only used to represent a set of operations or data. We can also use classes and inheritance to represent hierarchies through polymorphism. For instance, let’s say that we send a network request. As a result, we either successfully receive the requested data, or the request fails with some information about what went wrong. These two outcomes can be represented using two classes that implement an interface:
Press + to interact
interface Resultclass Success(val data: String) : Resultclass Failure(val exception: Throwable) : Result
Alternatively, we could use an abstract class:
Press + to interact
abstract class Resultclass Success(val data: String) : Result()class Failure(val exception: Throwable) : Result()
Restricted hierarchies
With either of these, we know that when a ...