why we use sealed classes i read documentation and...
# getting-started
m
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
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
@Joffrey it makes sense thank you