Enum Classes

    Each enum constant is an object. Enum constants are separated with commas.

    Since each enum is an instance of the enum class, they can be initialized as:

    1. RED(0xFF0000),
    2. GREEN(0x00FF00),
    3. BLUE(0x0000FF)
    4. }

    Enum constants can also declare their own anonymous classes with their corresponding methods, as well as overriding base methods.

    Enum entries cannot contain nested types other than inner classes (deprecated in Kotlin 1.2).

    An enum class may 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:

    1. import java.util.function.BinaryOperator
    2. import java.util.function.IntBinaryOperator
    3. enum class IntArithmetics : BinaryOperator<Int>, IntBinaryOperator {
    4. PLUS {
    5. override fun apply(t: Int, u: Int): Int = t + u
    6. },
    7. override fun apply(t: Int, u: Int): Int = t * u
    8. };
    9. override fun applyAsInt(t: Int, u: Int) = apply(t, u)
    10. }
    11. //sampleEnd
    12. val a = 13
    13. val b = 31
    14. for (f in IntArithmetics.values()) {
    15. println("$f($a, $b) = ${f.apply(a, b)}")
    16. }

    Enum classes in Kotlin have synthetic methods allowing to list the defined enum constants and to get an enum constant by its name. The signatures of these methods are as follows (assuming the name of the enum class is EnumClass):

    Since Kotlin 1.1, it’s possible to access the constants in an enum class in a generic way, using the enumValues<T>() and enumValueOf<T>() functions:

    1. enum class RGB { RED, GREEN, BLUE }
    2. inline fun <reified T : Enum<T>> printAllValues() {
    3. print(enumValues<T>().joinToString { it.name })
    4. }

    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.