简体   繁体   中英

What does it mean by: enum constant is a single instance but subclass of a sealed class can have multiple instances?

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:

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 (ie, 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 (ie, foo1 !== foo2 ) with different values for value (ie, different state).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM