0

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).

  • Is there something specific about the [documentation](https://kotlinlang.org/docs/sealed-classes.html) that you don't understand or feel it's not explaining well enough? It has a couple of examples of ways it might be used in practice. It is nothing like the Java `default` modifier. Does [question](https://stackoverflow.com/questions/50772328/what-are-sealed-classes-in-kotlin) explain what you want to know? – Tenfour04 Dec 07 '22 at 17:40
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Dec 08 '22 at 07:43

1 Answers1

1

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).

Pavel Shorokhov
  • 4,485
  • 1
  • 35
  • 44
  • To expand upon this, I use them to define UI events passed to non-visual layers. The sealed class might be AuthScreenEvent, and it might have sub-classes like UsernameEntered(userName:String) or LoginUser(). The ViewModel accepts an AuthScreenEvent, analyzes the event, and then acts accordingly. – eimmer Dec 07 '22 at 18:35