Kotlin Sealed Classes

168 views Asked by At

I am new to Kotlin Programming

What are the real time examples of Sealed Classes. If the implemented classes are not sealed then it can be further inherited. What's the use in it?. Is Sealed class same as default modifier in java. (Except the when condition case what is the real world usage of sealed classes and When to use sealed classes).

1

There are 1 answers

1
Pavel Shorokhov On

The main benefit of sealed classes - it has limited inherited-classes, known at compile-time.

So you can do when () {...}, and be sure you are specified all possible items, omitting else case.

If you add a new child to sealed-class, compiler show you all places, where you need to specify extra behaviors (all when-statements, where it is using).