Seals are not just sea mammals
A guide through Kotlin's 'sealed' keyword and what you can do with it.
|Philipp Jahoda||Aug 26, 2018||2|
The more time you spend using Kotlin, the more you are going to realize how magnificent of a language it actually is. I just recently hit a new “peak” of admiration for this language by discovering the
Have a look at the code sample below:
We have a
sealed class Response, representing the response from e.g. a network request and two data classes (
Error) derived from
Response. At first glance, this looks like nothing more than a simple example of inheritance (and some mixed in generics), when in fact it is a very clever way of using actual classes (and the increased possibilities that go along with them) as
Let’s spin this a little bit further:
The magic behind all this is the fact that Kotlin allows you to use
sealed classes as cases for the
when() statement - by doing so, the classes shown above are nothing more than a complex enum with added functionality.
main() function above clearly shows the benefit of being able to create a function like
print(response: Response) without having to worry about the actual type being passed to the function.
The output of the main function obviously looks as follows:
I hope this short post could give you a quick insight into the nature of Kotlin’s
sealed keyword and will help you to write cleaner and easier maintainable code in the future.
In case you enjoy reading this daily newsletter, please consider sharing it with your coworkers. Send them this link to sign up: https://philjay.substack.com/
I would love to hear your feedback on this newsletter. If you have something to say, just let me know.
Inspired by the post of Piotr Ślesarew on medium.com