Daily Coding

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
Comment
Share

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

CommentComment
ShareShare

Create your profile

0 subscriptions will be displayed on your profile (edit)

Skip for now

Only paid subscribers can comment on this post

Already a paid subscriber? Sign in

Check your email

For your security, we need to re-authenticate you.

Click the link we sent to , or click here to sign in.

Ready for more?

© 2022 Philipp Jahoda
Privacy ∙ Terms ∙ Collection notice
Publish on Substack Get the app
Substack is the home for great writing