TExcelTAD
Home › Kotlin › Kotlin Enum Classes

Kotlin Enum Classes

An enum (enumeration) is a type with a fixed, known set of values: the days of the week, the suits of a card deck, the states of an order. Using an enum instead of strings or numbers means typos become compile errors and when can check that you handled every case.

Declaring an enum

kotlin · try it yourself
enum class Direction { NORTH, EAST, SOUTH, WEST }

fun main() {
    val heading = Direction.EAST
    println(heading)
    println(heading.name)
    println(heading.ordinal)     // position, starting at 0
    println(heading == Direction.EAST)
}
EAST
EAST
1
true

Each value (NORTH, EAST, …) is a single object — an enum constant. By convention they're written in upper case.

Enums and when

when over an enum doesn't need an else branch if every constant is covered. If someone later adds a new constant, the compiler points to every when that must be updated.

kotlin · try it yourself
enum class Light { RED, YELLOW, GREEN }

fun action(light: Light) = when (light) {
    Light.RED -> "Stop"
    Light.YELLOW -> "Get ready"
    Light.GREEN -> "Go"
}

fun main() {
    for (l in Light.entries) println("$l: ${action(l)}")
}
RED: Stop
YELLOW: Get ready
GREEN: Go

Light.entries is a list of all constants in declaration order (older code uses values(), which returns an array).

Properties and functions

Enum constants can carry data through a constructor, and the enum can have functions:

kotlin · try it yourself
enum class Planet(val massKg: Double, val radiusM: Double) {
    MERCURY(3.303e23, 2.4397e6),
    EARTH(5.976e24, 6.37814e6),
    JUPITER(1.9e27, 7.1492e7);       // semicolon before members

    fun surfaceGravity(): Double = 6.67300E-11 * massKg / (radiusM * radiusM)
}

fun main() {
    for (p in Planet.entries) {
        println("${p.name.lowercase()}: ${"%.2f".format(p.surfaceGravity())} m/s²")
    }
}
mercury: 3.70 m/s²
earth: 9.80 m/s²
jupiter: 24.81 m/s²

Note the semicolon after the last constant: it's required when the enum has a body with members.

Looking up constants

kotlin · try it yourself
enum class Size(val label: String) { S("small"), M("medium"), L("large") }

fun main() {
    println(Size.valueOf("M").label)
    println(Size.entries.map { it.label })
    println(Size.entries.firstOrNull { it.label == "large" })
    println(Size.entries.find { it.name == "XL" })
}
medium
[small, medium, large]
L
null

valueOf("XL") would throw an IllegalArgumentException; searching entries with find/firstOrNull returns null instead.

Constant-specific behaviour

Each constant can override an abstract function declared by the enum:

kotlin · try it yourself
enum class Operation(val symbol: String) {
    ADD("+") { override fun apply(a: Int, b: Int) = a + b },
    SUB("-") { override fun apply(a: Int, b: Int) = a - b },
    MUL("*") { 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("7 ${op.symbol} 3 = ${op.apply(7, 3)}")
    }
}
7 + 3 = 10
7 - 3 = 4
7 * 3 = 21

Built-in members

Member Meaning
name the constant's name as a String
ordinal its position (0-based)
Enum.entries list of all constants
Enum.valueOf(s) the constant with that name (throws if none)
compareTo enums are comparable by ordinal

Tip: Enums are perfect when every value has the same shape. When different cases need different data (e.g. Success(data) vs Error(message)), use a sealed class — next chapter.

Test yourself

What is Direction.SOUTH.ordinal for enum class Direction { NORTH, EAST, SOUTH, WEST }?

  1. 3
  2. 2
  3. 1
  4. "SOUTH"

Why can a when over an enum skip the else branch?

  1. Enums are always non-null
  2. The compiler knows all constants and checks that each is handled
  3. else is never needed in Kotlin
  4. Enums are strings

When is a semicolon required in an enum class?

  1. Never
  2. After every constant
  3. After the last constant when members follow
  4. Before the first constant