Enums

The enum keyword defines enum class.

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

 // simple enum
enum class RGB { RED, GREEN, BLUE }

// enum with constructor
enum class Color(val rgb: Int) {
        RED(0xFF0000),
        GREEN(0x00FF00),
        BLUE(0x0000FF)
}

// example of using enumValues
inline fun <reified T : Enum<T>> printAllValues() {
    print(enumValues<T>().joinToString { it.name })
}

printAllValues<RGB>() // prints RED, GREEN, BLUE
property description
name Name of enum's constant.
ordinal Position of constant in enum.
static
method description
valueOf(name) Return enum's constant by its name. Throws an IllegalArgumentException if the specified name does not match any of the enum constants defined in the class.
values() Returns array of all constants in enum class.
enumValueOf(name) Return enum's constant by its name. This is generic version of the valueOf method.
enumValues() Returns array of all constants in enum class. This is generic version of the values method.

enum with interface

An enum class may implement an interface, but not derive from a class. You can provide either a single interface members implementation for all of the entries, or separate ones for each entry within its anonymous class.

// enum that implements interfaces
enum class IntArithmetics : BinaryOperator<Int>, IntBinaryOperator {
    PLUS {
        override fun apply(t: Int, u: Int): Int = t + u
    },
    TIMES {
        override fun apply(t: Int, u: Int): Int = t * u
    };

    override fun applyAsInt(t: Int, u: Int) = apply(t, u)
}

enum with anonymous classes

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

enum class ProtocolState {
    WAITING {
        override fun signal() = TALKING
    },

    TALKING {
        override fun signal() = WAITING
    };

    abstract fun signal(): ProtocolState
}