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.
CodePudding user response:
Enums
You cannot instantiate enum classes yourself. The instances are managed by the language/run-time. So, if you have the following enum class:
enum class Foo(val value: Int) {
ONE(4), TWO(2)
}
Then the only instances of Foo
are ONE
and TWO
. You reference these instances using Foo.ONE
and Foo.TWO
. Note that these constants have state (though they don't have to) in the form of the value
property. But every single reference to Foo.ONE
will have the same value for value
, because there is only one instance per constant (i.e., Foo.ONE === Foo.ONE
). Same with Foo.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 sealed
class as they can't be instantiated). For example:
sealed class Foo
class IntFoo(val value: Int) : Foo()
class StringFoo(val value: String) : Foo()
With this you can create as many instances of both IntFoo
and StringFoo
as you want.
val foo1 = IntFoo(4)
val foo2 = IntFoo(2)
That code creates two instances of IntFoo
(i.e., foo1 !== foo2
) with different values for value
(i.e., different state).