Enum classes
The most basic usage of enum classes is implementing type-safe enums:
Each enum constant is an object. Enum constants are separated with commas.
Since each enum is an instance of the enum class, it can be initialized as:
Anonymous classes
Enum constants can also declare their own anonymous classes with their corresponding methods, as well as overriding base methods.
If the enum class defines any members, separate the enum constant definitions from the member definitions with a semicolon.
Implementing interfaces in enum classes
An enum class can implement an interface (but not derive from a class), providing either a single interface members implementation for all of the entries, or separate ones for each entry within its anonymous class. This is done by adding the interfaces to the enum class declaration as follows:
Working with enum constants
Enum classes in Kotlin have synthetic 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
):
The valueOf()
method throws an IllegalArgumentException
if the specified name does not match any of the enum constants defined in the class.
You can access the constants in an enum class in a generic way, using the enumValues<T>()
and enumValueOf<T>()
functions:
Every enum constant has properties to obtain its name and position in the enum class declaration:
The enum constants also implement the Comparable interface, with the natural order being the order in which they are defined in the enum class.