https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Muhammet Emin Gündoğar

09/07/2021, 10:11 AM
why we use sealed classes i read documentation and i use it in deciding situations in android like error,success but i want to ask why we use sealed classes instead of normal class or enums what is the advantages of sealed class over them?
j

Joffrey

09/07/2021, 10:18 AM
Sealed classes are like meta-enums. An enum is a single type with a finite set of values. A sealed class is a type hierarchy with a finite set of subtypes, each of which can have arbitrary many values. It is useful when you want to represent values of different types (for instance with different properties) but you also want to be able to exhaustively check these types in a
when
(which you woudn't be able to do with regular inheritance hierarchy)
Your success/error example is a decent example. Having a sealed class to represent a result like this allows to declare precisely 2 possible types of return values, both of them having a different set of properties (success probably encapsulates some value of a generic type, while error encapsulates probably an exception, or a message, or a code). With enums you wouldn't be able to return infinitely many different success values. With regular type hierarchies, users wouldn't be able to be certain there is no other implementations than Success and Error.
m

Muhammet Emin Gündoğar

09/07/2021, 10:35 AM
@Joffrey it makes sense thank you