Skip to content
AgileLogics
5 min read

Enum Classes

Prerequisites: The when expression, Classes and objects

An enum class defines a type with a fixed set of possible values. Use one whenever a value must be one of a known list of options.

Example

enum class Direction { NORTH, SOUTH, EAST, WEST }

fun arrow(d: Direction) = when (d) {
    Direction.NORTH -> "↑"
    Direction.SOUTH -> "↓"
    Direction.EAST -> "→"
    Direction.WEST -> "←"
}

fun main() {
    val heading = Direction.EAST
    println(heading)
    println(arrow(heading))
    println(heading.ordinal)
    println(Direction.valueOf("WEST"))
    println(Direction.entries)
}

Expected output

EAST
→
2
WEST
[NORTH, SOUTH, EAST, WEST]
  • The when needs no else: it covers every value. If you add a new direction later, the compiler reports every when that doesn't handle it.
  • ordinal is the position (from 0); name is the text.
  • valueOf("WEST") converts text to an enum value (and throws for unknown text).
  • entries lists every value, in order.

Properties and methods

Enum values can carry data, and enums can have methods:

enum class Size(val ml: Int, val price: Double) {
    SMALL(250, 2.5),
    MEDIUM(350, 3.0),
    LARGE(450, 3.5);

    fun label() = "${name.lowercase()} (${ml}ml): $$price"
}

fun main() {
    for (size in Size.entries) {
        println(size.label())
    }
}
small (250ml): $2.5
medium (350ml): $3.0
large (450ml): $3.5

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

Common mistakes

  • Using strings like "small" for a fixed set of options. A typo in a string is a silent bug; a typo in an enum value is a compile error.
  • Adding an else branch to a when over your own enum. It hides the compile error you'd otherwise get when a new value is added.