Daily Coding

Daily Coding

A daily newsletter focusing on coding with Kotlin, Swift and Java.

By Philipp Jahoda
· Launched 5 years ago
By registering you agree to Substack's Terms of Service, our Privacy Policy, and our Information Collection Notice
Share this post

Seals are not just sea mammals

philjay.substack.com

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
Share this post

Seals are not just sea mammals

philjay.substack.com

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 sealed keyword.

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 (Success & 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 enums.

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.

The 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:

500
Request Successful

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

View comments

Share this post

Seals are not just sea mammals

philjay.substack.com
Comments

Ready for more?

© 2023 Philipp Jahoda
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing