Enum classes
The most basic use case for enum classes is the implementation of type-safe enums:
Each enum constant is an object. Enum constants are separated by commas.
Since each enum is an instance of the enum class, it can be initialized as:
Anonymous classes
Enum constants can declare their own anonymous classes with their corresponding methods, as well as with overriding base methods.
If the enum class defines any members, separate the constant definitions from the member definitions with a semicolon.
Implementing interfaces in enum classes
An enum class can implement an interface (but it cannot derive from a class), providing either a common implementation of interface members for all the entries, or separate implementations for each entry within its anonymous class. This is done by adding the interfaces you want to implement to the enum class declaration as follows:
All enum classes implement the Comparable interface by default. Constants in the enum class are defined in the natural order. For more information, see Ordering.
Working with enum constants
Enum classes in Kotlin have synthetic properties and methods for listing the defined enum constants and getting an enum constant by its name. The signatures of these methods are as follows (assuming the name of the enum class is EnumClass
):
Below is an example of them in action:
The valueOf()
method throws an IllegalArgumentException
if the specified name does not match any of the enum constants defined in the class.
Prior to the introduction of entries
in Kotlin 1.9.0, the values()
function was used to retrieve an array of enum constants.
Every enum constant also has properties: name
and ordinal
, for obtaining its name and position (starting from 0) in the enum class declaration:
You can access the constants in an enum class in a generic way using the enumValues<T>()
and enumValueOf<T>()
functions. In Kotlin 2.0.0, the enumEntries<T>()
function is introduced as a replacement for the enumValues<T>()
function. The enumEntries<T>()
function returns a list of all enum entries for the given enum type T
.
The enumValues<T>()
function is still supported, but we recommend that you use the enumEntries<T>()
function instead because it has less performance impact. Every time you call enumValues<T>()
a new array is created, whereas whenever you call enumEntries<T>()
the same list is returned each time, which is far more efficient.
For example: