I am trying to understand:
Kotlin Sealed Class Official Doc
But I am struggling to understand the phrase:
each enum constant exists only as a single instance, whereas a subclass of a sealed class can have multiple instances, each with its own state.
What does that mean? An example will help.
Enums
You cannot instantiate enum classes yourself. The instances are managed by the language/run-time. So, if you have the following enum class:
Then the only instances of
FooareONEandTWO. You reference these instances usingFoo.ONEandFoo.TWO. Note that these constants have state (though they don't have to) in the form of thevalueproperty. But every single reference toFoo.ONEwill have the same value forvalue, because there is only one instance per constant (i.e.,Foo.ONE === Foo.ONE). Same withFoo.TWO.Sealed Classes
Sealed classes are different. They restrict the class hierarchy to a known set of classes, but they do not prevent you from instantiating the classes as you need (except for the
sealedclass as they can't be instantiated). For example:With this you can create as many instances of both
IntFooandStringFooas you want.That code creates two instances of
IntFoo(i.e.,foo1 !== foo2) with different values forvalue(i.e., different state).