Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 134 ยท Classes and Objects

Enum Classes

Learn Kotlin enum classes: constants with properties and methods, entries, valueOf, ordinal, abstract members per constant, exhaustive when, EnumMap and enum pitfalls.

Some values come from a small, fixed list: the days of the week, the suits in a deck of cards, the states of an order (PENDING, PAID, SHIPPED). Storing them as strings or integers invites mistakes, since nothing stops you from writing "shiped" or 7. An enum class makes the list a real type. A variable of type Suit can only be one of the declared constants, and the compiler checks every use.

In Kotlin an enum is more than a list of names. Each constant is an object. It can carry properties, implement functions, and even override behavior of its own. This lesson covers the basics, the modern entries property, enums with data and behavior, when over enums, and the traps that catch beginners and professionals alike. For choosing between enums and class hierarchies, read Sealed Classes and Interfaces afterwards.

Declaring and using an enum

Kotlin The simplest enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Every enum constant has two built-in properties: name, the identifier as a string, and ordinal, its zero-based position in the declaration. Printing a constant prints its name. Enums are comparable by declaration order, and == compares identity, which is safe because each constant exists exactly once.

Constants are conventionally written in UPPER_SNAKE_CASE.

Listing all constants: entries

To walk over all constants, use the entries property, which returns an immutable list of every constant in declaration order:

Kotlin entries and valueOf

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Level.valueOf("HIGH") converts a string to a constant, and it throws IllegalArgumentException for any name that does not exist; the message names the enum and the bad value. When the string comes from user input or a file, use entries.firstOrNull { ... } (or write a small lookup function) to get null instead of an exception.

Older code uses Level.values(), which allocates a new array on every call. Since Kotlin 1.9 prefer entries: it is a shared, immutable list, so it is cheaper and works with all the collection functions. values() is only worth knowing so you can read older code, and enumValues<T>() has the modern twin enumEntries<T>() for generic code.

Enums with properties and methods

Because each constant is an object, an enum can have a constructor. Pass the values in parentheses after each constant, and add members after a semicolon that ends the constant list:

Kotlin Constants with data and behavior

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The semicolon after the last constant is required whenever members follow. Forgetting it is a common compile error. The enum's constructor is always private, so you cannot create new constants at run time, and that is the whole point.

Each constant with its own behavior

Constants can have a body, in which they override members declared in the enum. If the enum declares an abstract member, every constant must provide it:

Kotlin Abstract members implemented per constant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This is the strategy pattern without any when: the behavior lives next to the data it belongs to, and adding a constant forces you to supply its behavior, because the compiler will not let a constant skip an abstract member. Use this style when each constant differs in how it works. Use a plain property when constants differ only in what values they hold.

Enums and when

when and enums fit together perfectly. When you use when as an expression over an enum, the compiler requires every constant to be covered (or an else), and the benefit is large: add a new constant later and every when that forgot it stops compiling.

Kotlin Exhaustive when over an enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first when has no else. That is deliberate: it makes the compiler your safety net. See what happens if one case is missing:

Kotlin A missing enum case (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler stops with error: 'when' expression must be exhaustive. Add the 'SHIPPED' branch or an 'else' branch. Be careful with else: it silences exactly this protection, because a future constant would fall into it silently. Prefer listing constants explicitly when you want the compiler's help. For more on when, see when Expressions.

Enums implementing interfaces

Enums can implement interfaces but cannot extend classes (every enum already extends Enum). The interface member is then implemented once in the enum or per constant:

Kotlin An enum implementing an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The trailing comma after MOCHA(420) is allowed and makes adding the next constant a one-line change in version control.

Collections made for enums

Enum constants make excellent keys. The JDK provides EnumMap and EnumSet, which store values in an array indexed by ordinal, so they are compact and fast. In Kotlin you can also simply use associateWith or groupBy:

Kotlin Maps keyed by enum constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

EnumMap always iterates in ordinal order, whatever the insertion order, which is why MON prints before FRI above. A plain mapOf keeps insertion order instead.

Pitfalls and design notes

  • Do not store ordinal or rely on it. Reordering or inserting a constant changes every ordinal. If you save numbers in a file or database, give the enum an explicit code property and look it up by that.
  • Names are API. Renaming a constant changes name, toString() and what valueOf accepts. When a name is stored or sent over the network, treat it as a contract.
  • Enums cannot be extended. All constants are known at compile time. If the set of cases must grow, or the cases need different data, use a sealed hierarchy.
  • Keep behavior small. An enum with a hundred lines of logic in every constant is a class hierarchy in disguise.
  • Defaults with entries. entries.first() is a handy default constant; entries.last() the opposite.

Finally, enums are singletons, so they are thread-safe by construction and are cheap to compare with ==. They also work as conditions in when without type checks, since there is nothing to smart-cast.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the modern way to iterate over all constants of enum class Level?

    entries is an immutable list shared by all callers. values() still exists but allocates a new array each time, so entries is preferred since Kotlin 1.9.
  2. 2. What happens when you call Level.valueOf("ULTRA") and no such constant exists?

    valueOf throws IllegalArgumentException for unknown names. Use entries.firstOrNull { it.name == text } when you want null.
  3. 3. Why should an exhaustive when over an enum usually avoid an else branch?

    An else branch would silently handle future constants, hiding places that need updating. Listing constants makes the compiler find them.
  4. 4. What is required in an enum that declares properties or functions after its constants?

    The semicolon separates the constant list from the members that follow it.
  5. 5. Which is a good reason NOT to save ordinal in a database?

    ordinal is just the declaration position, so any edit to the declaration order changes it. Use an explicit stable code property.

Summary

  • An enum class is a type with a fixed set of constants, each a singleton object with name and ordinal.
  • Use entries (not values()) to list constants; valueOf throws for unknown names.
  • Constants can carry constructor data, members, and individual bodies that implement abstract members.
  • when over an enum is exhaustive without else, and the compiler flags any constant you forget.
  • Enums can implement interfaces but cannot be extended; use sealed hierarchies for open-ended or data-varying cases.
  • EnumMap and EnumSet are compact collections keyed by constants; never persist ordinal.

Next: Sealed Classes and Interfaces