Kotlin Sealed Classes | raywenderlich.com

In this Android tutorial, see how to use Kotlin sealed classes to create limited hierarchies that act like enums but allow you to create multiple instances.

This is a companion discussion topic for the original entry at https://www.raywenderlich.com/75657-kotlin-sealed-classes

This tutorial is really good! is there any recommended tutorial can you suggest for MVI?

hi @simplekjl thanks for the question!

We have a tutorial that covers MVI here: https://www.raywenderlich.com/817602-mvi-architecture-for-android-tutorial-getting-started

We also have a video course: https://www.raywenderlich.com/266607-mvi-on-android

And MVI is discussed extensively in our book “Advanced Android App Architecture”: https://store.raywenderlich.com/products/advanced-android-app-architecture

Thanks again for the question!

Thanks for doing this! It reminds me of the C++ days where you had to turn ON polymorphism with the key word ‘virtual’ but in Java you turned it OFF with the key word final.

C++ had the concept of ‘inline’ which is a lot like how Java does final static values. At the compiler level it just copies that code ‘inline’. A common bug around that was to not do a ‘clean’ build and an old .class file (Java) would have the OLD static final value.

I remember reading about how the Math package in Java was made final for large speed improvements.

Sealed Classes makes me think I get my cake and can also eat it. :slight_smile:

Sadly, I think nobody talks anymore about VTables and the cost of late binding. Objective C has a really cool feature where you can change the VTable array to put your own behavior in EVEN if it is a legacy API call which is pretty neat. (Method Swizzling)

Interesting how the Kotlin authors tried to go for this ideal ‘sweet spot’. I would think this optimizes many things including compile time, run time optimizations as well as very maintainable code base.

thanks , for the article
but I have a question. I did everything step-by-step in this article.
I don’t understend the term " limited hierarchies". Since i use “open” word, for any class i want, I can do many subclasses for a sealed class’ children too.

open class Crypto : AcceptedCurrency(){
override val valueInDollars: Double = 3000.5

class ANewClass: Crypto(){


I expect an error with ANewClass declaration here, but it looks ok for the IDE …

Thanks for the question, @alexkoto! The word “limited” in this case means finite or small, as in finite or small in number. As in, there will only a known small number of subclasses.

This tutorial is more than six months old so questions are no longer supported at the moment for it. Thank you!