Enums with Abstract Members and Interfaces

Different Behaviour per Constant

Example

Each constant can override an abstract function in its own body.

enum class Operation(val symbol: String) {
    ADD("+") { override fun apply(a: Int, b: Int) = a + b },
    SUBTRACT("-") { override fun apply(a: Int, b: Int) = a - b },
    MULTIPLY("x") { override fun apply(a: Int, b: Int) = a * b };

    abstract fun apply(a: Int, b: Int): Int
}

fun main() {
    for (op in Operation.entries) println("12 ${op.symbol} 4 = ${op.apply(12, 4)}")
}

Output

12 + 4 = 16
12 - 4 = 8
12 x 4 = 48

Implementing an Interface

Example

interface HasColor { val hex: String }

enum class Priority(override val hex: String) : HasColor {
    LOW("#4CAF50"), MEDIUM("#FFC107"), HIGH("#F44336")
}

fun main() {
    val sorted = listOf(Priority.HIGH, Priority.LOW, Priority.MEDIUM).sorted()  // by ordinal
    sorted.forEach { println("${it.name} ${it.hex}") }
}

Output

LOW #4CAF50
MEDIUM #FFC107
HIGH #F44336

Note: Enums are Comparable by their declaration order (ordinal), so sorted() and < work out of the box.