Enum entries

suggest change

Every enum class has a static entries property: a read-only List of all its constants, in declaration order. It replaces the old values() function, which returns a new array on every call.

enum class Color { RED, GREEN, BLUE }

val all: List<Color> = Color.entries   // [RED, GREEN, BLUE]

Versions:

All the examples below were compiled and run with Kotlin 2.4.21 on JDK 25.

The basics of enum classes (name, ordinal, valueOf, constructors) are covered in Enum and Simple enum. This article is about listing and looking up constants.

The entries list

entries has type EnumEntries<E>, which is a List<E>. You get everything a list offers: size, indexing, indexOf, iteration and the whole collection API:

enum class Color { RED, GREEN, BLUE }

fun main() {
    val all = Color.entries
    println(all)
    println(all.size)
    println(all[1])
    println(all.first() to all.last())
    println(all.indexOf(Color.BLUE))
    for (c in Color.entries) {
        println("${c.ordinal}: ${c.name}")
    }
    println(all::class.qualifiedName)
}
[RED, GREEN, BLUE]
3
GREEN
(RED, BLUE)
2
0: RED
1: GREEN
2: BLUE
kotlin.enums.EnumEntriesList

The order is the declaration order, so entries[c.ordinal] == c for every constant.

entries vs values()

values() comes from Java. It returns an Array, and because arrays are mutable it has to return a fresh copy every time. Otherwise one caller could overwrite elements and break the enum for everybody else.

entries is created once, when the enum class is initialized, and the same immutable list is returned on every access:

enum class Color { RED, GREEN, BLUE }

fun main() {
    println(Color.values() === Color.values())    // a new array every call
    println(Color.entries === Color.entries)      // the same list every time

    val arr = Color.values()
    arr[0] = Color.BLUE                           // arrays are mutable
    println(arr.contentToString())
    println(Color.values().contentToString())     // the enum itself is unaffected

    val list = Color.entries
    // list[0] = Color.BLUE                       // doesn't compile: List is read-only
    try {
        @Suppress("UNCHECKED_CAST")
        (list as MutableList<Color>).add(Color.RED)
    } catch (e: ClassCastException) {
        println("not a MutableList: ${e.message}")
    }
}
false
true
[BLUE, GREEN, BLUE]
[RED, GREEN, BLUE]
not a MutableList: kotlin.enums.EnumEntriesList cannot be cast to kotlin.collections.MutableList

Even a cast to MutableList fails, so there's no way to change the list.

The copy made by values() is small but it adds up in hot code, such as a parser that looks up an enum for every token. Here's the allocation per call measured with the JVM's per-thread allocation counter:

import java.lang.management.ManagementFactory
import com.sun.management.ThreadMXBean

enum class Level { TRACE, DEBUG, INFO, WARN, ERROR, FATAL }

val mx = ManagementFactory.getThreadMXBean() as ThreadMXBean

inline fun allocated(block: () -> Unit): Long {
    val id = Thread.currentThread().threadId()
    val before = mx.getThreadAllocatedBytes(id)
    block()
    return mx.getThreadAllocatedBytes(id) - before
}

fun main() {
    var sink = 0
    repeat(3) {            // warm up so JIT and class loading don't count
        allocated { repeat(1_000_000) { sink += Level.values().size } }
        allocated { repeat(1_000_000) { sink += Level.entries.size } }
    }
    val v = allocated { repeat(1_000_000) { sink += Level.values()[it % 6].ordinal } }
    val e = allocated { repeat(1_000_000) { sink += Level.entries[it % 6].ordinal } }
    println("values():  ${v / 1_000_000} bytes per call")
    println("entries:   ${e / 1_000_000} bytes per call")
    println(sink > 0)
}
values():  40 bytes per call
entries:   0 bytes per call
true

40 bytes is the array header plus six references. A million calls produce 40 MB of garbage for nothing. With entries there's nothing to allocate.

The other benefit is the API. List has getOrNull, subList, indexOf and equality, works with every function that takes a List or Collection, and doesn't need contentToString() to print.

Using collection functions

Since entries is a list, queries over the constants read naturally:

enum class Planet(val massKg: Double, val radiusM: Double, val rocky: Boolean) {
    MERCURY(3.303e23, 2.4397e6, true),
    VENUS(4.869e24, 6.0518e6, true),
    EARTH(5.976e24, 6.37814e6, true),
    MARS(6.421e23, 3.3972e6, true),
    JUPITER(1.9e27, 7.1492e7, false),
    SATURN(5.688e26, 6.0268e7, false),
    URANUS(8.686e25, 2.5559e7, false),
    NEPTUNE(1.024e26, 2.4746e7, false);
}

fun main() {
    println(Planet.entries.filter { it.rocky })
    println(Planet.entries.maxBy { it.massKg })
    println(Planet.entries.sortedBy { it.radiusM }.take(3))
    println(Planet.entries.map { it.name.lowercase() }.joinToString())
    println(Planet.entries.partition { it.rocky }.second.size)
    println(Planet.entries.subList(2, 5))
    println(Planet.entries.zipWithNext().first())
    println(Planet.entries.groupBy({ it.rocky }, { it.name.take(3) }))
    println(Planet.EARTH in Planet.entries.takeWhile { it.rocky })
}
[MERCURY, VENUS, EARTH, MARS]
JUPITER
[MERCURY, MARS, VENUS]
mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
4
[EARTH, MARS, JUPITER]
(MERCURY, VENUS)
{true=[MER, VEN, EAR, MAR], false=[JUP, SAT, URA, NEP]}
true

Other handy ones: Color.entries.random() for test data, and Color.entries.toTypedArray() when a Java API really wants an array.

Cycling through constants

entries and ordinal together give you "next" and "previous" without listing the constants a second time. Inside the enum class you can write just entries:

enum class Light {
    RED, GREEN, YELLOW;

    fun next(): Light = entries[(ordinal + 1) % entries.size]
    fun previous(): Light = entries[(ordinal - 1 + entries.size) % entries.size]
}

fun main() {
    var light = Light.RED
    repeat(4) {
        print("$light -> ")
        light = light.next()
    }
    println(light)
    println(Light.RED.previous())
}
RED -> GREEN -> YELLOW -> RED -> GREEN
YELLOW

Adding a constant later doesn't require touching next().

EnumSet and EnumMap

On the JVM, EnumSet and EnumMap are compact, fast collections keyed by enum constants. entries combines well with them:

import java.util.EnumMap
import java.util.EnumSet

enum class Perm { READ, WRITE, EXECUTE, ADMIN }

fun main() {
    val user = EnumSet.of(Perm.READ, Perm.WRITE)
    val missing = Perm.entries.filterNot { it in user }
    println(missing)

    val all = EnumSet.copyOf(Perm.entries)
    println(all)

    // a count for every constant, including zeros
    val log = listOf(Perm.READ, Perm.READ, Perm.WRITE, Perm.READ)
    val counts = Perm.entries.associateWithTo(EnumMap(Perm::class.java)) { p -> log.count { it == p } }
    println(counts)
}
[EXECUTE, ADMIN]
[READ, WRITE, EXECUTE, ADMIN]
{READ=3, WRITE=1, EXECUTE=0, ADMIN=0}

Starting from entries guarantees every constant gets a key, which matters for reports and metrics where a zero is still a value.

Looking up a constant by name

valueOf() returns the constant with exactly that name and throws IllegalArgumentException when there's none. For input from users, files or the network you usually want null instead, and often a case-insensitive match:

enum class Status { ACTIVE, SUSPENDED, DELETED }

fun main() {
    println(Status.valueOf("ACTIVE"))
    try {
        Status.valueOf("active")
    } catch (e: IllegalArgumentException) {
        println(e.message)
    }

    // safe lookups
    println(Status.entries.firstOrNull { it.name == "PENDING" })
    println(Status.entries.firstOrNull { it.name.equals("suspended", ignoreCase = true) })
    println(runCatching { Status.valueOf("PENDING") }.getOrNull())
}
ACTIVE
No enum constant Status.active
null
SUSPENDED
null

Prefer the entries.firstOrNull version over runCatching. Using exceptions for an expected "not found" result is slower and catches more than you meant to.

Looking up by a property

Enums often carry a code that is stored or sent over the wire. Build a map from entries once, in the companion object, and use it for lookups:

enum class HttpStatus(val code: Int, val reason: String) {
    OK(200, "OK"),
    CREATED(201, "Created"),
    NOT_FOUND(404, "Not Found"),
    INTERNAL_ERROR(500, "Internal Server Error");

    companion object {
        private val byCode = entries.associateBy { it.code }

        fun fromCode(code: Int): HttpStatus? = byCode[code]
        fun fromName(name: String): HttpStatus? =
            entries.find { it.name.equals(name, ignoreCase = true) }
    }
}

fun main() {
    println(HttpStatus.fromCode(404))
    println(HttpStatus.fromCode(418))
    println(HttpStatus.fromName("created")?.code)
    println(HttpStatus.fromCode(500)?.reason ?: "unknown")
}
NOT_FOUND
null
201
Internal Server Error

For a handful of constants a linear entries.find is just as fast as a map. The map pays off for larger enums or very frequent lookups.

Don't use entries in an enum constructor

The companion object is initialized after all constants are created, so using entries there is safe. The enum's own init block is different: it runs while the constants are being constructed, before entries exists:

enum class Step(val label: String) {
    FIRST("first"), SECOND("second"), THIRD("third");

    init {
        println("init $label, entries = ${runCatching { entries.size }}")
    }
}

fun main() {
    println(Step.entries)
}
init first, entries = Failure(java.lang.NullPointerException: Cannot invoke "kotlin.enums.EnumEntries.size()" because the return value of "Step.getEntries()" is null)
init second, entries = Failure(java.lang.NullPointerException: Cannot invoke "kotlin.enums.EnumEntries.size()" because the return value of "Step.getEntries()" is null)
init third, entries = Failure(java.lang.NullPointerException: Cannot invoke "kotlin.enums.EnumEntries.size()" because the return value of "Step.getEntries()" is null)
[FIRST, SECOND, THIRD]

The compiler doesn't warn about it. Move such logic into the companion object or a lazily computed property. The same applies to values().

Generic code: enumEntries()

In a function that works with any enum type you can't write T.entries. Use enumEntries<T>() from kotlin.enums with a reified type parameter instead:

import kotlin.enums.enumEntries

enum class Color { RED, GREEN, BLUE }
enum class Size { S, M, L, XL }

inline fun <reified T : Enum<T>> parseEnum(s: String): T? =
    enumEntries<T>().firstOrNull { it.name.equals(s.trim(), ignoreCase = true) }

inline fun <reified T : Enum<T>> choices(): String =
    enumEntries<T>().joinToString("|") { it.name.lowercase() }

fun main() {
    println(parseEnum<Color>(" green "))
    println(parseEnum<Size>("xl"))
    println(parseEnum<Size>("XXL"))
    println(choices<Size>())

    val s: Size? = parseEnum("m")     // T inferred from the expected type
    println(s)

    println(enumEntries<Color>() === Color.entries)
    println(enumValueOf<Color>("BLUE"))
}
GREEN
XL
null
s|m|l|xl
M
true
BLUE

enumEntries<Color>() returns the very same list as Color.entries, so there's no allocation. enumValueOf<T>(name) is the generic version of valueOf and throws just like it. parseEnum above is a reusable safe replacement for it, useful for parsing command-line options or configuration values.

enumEntries needs reified, which means the function must be inline. If you don't want that, take the entries as a parameter. The caller passes Color.entries:

import kotlin.enums.EnumEntries

enum class Color { RED, GREEN, BLUE }
enum class Size { S, M, L, XL }

// no reified type parameter needed: the caller passes the entries
fun <E : Enum<E>> menu(title: String, options: EnumEntries<E>): String =
    options.joinToString(prefix = "$title: ", separator = ", ") { "${it.ordinal + 1}) ${it.name}" }

fun <E : Enum<E>> pick(options: EnumEntries<E>, choice: Int): E? = options.getOrNull(choice - 1)

fun main() {
    println(menu("Color", Color.entries))
    println(menu("Size", Size.entries))
    println(pick(Size.entries, 3))
    println(pick(Size.entries, 9))
}
Color: 1) RED, 2) GREEN, 3) BLUE
Size: 1) S, 2) M, 3) L, 4) XL
L
null

Java enums

entries also works on Java enums, including those in the JDK:

import java.time.DayOfWeek
import java.time.Month
import java.util.concurrent.TimeUnit

fun main() {
    println(DayOfWeek.entries.take(5))
    println(Month.entries.filter { it.length(false) == 30 })
    println(TimeUnit.entries.last())
}
[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY]
[APRIL, JUNE, SEPTEMBER, NOVEMBER]
DAYS

Java enums have no entries field, so the Kotlin compiler generates a small helper class in your code (named like MainKt$EntriesMappings) that calls values() once and caches the list. The same happens for Kotlin enums from libraries compiled before 1.8.20. You still get one shared list.

What the compiler generates

For a Kotlin enum, javap shows the cached list next to the classic array:

public final class Color extends java.lang.Enum<Color> {
  public static final Color RED;
  public static final Color GREEN;
  public static final Color BLUE;
  private static final Color[] $VALUES;
  private static final kotlin.enums.EnumEntries $ENTRIES;
  private Color();
  public static Color[] values();
  public static Color valueOf(java.lang.String);
  public static kotlin.enums.EnumEntries<Color> getEntries();
  private static final Color[] $values();
  static {};
}

values() clones $VALUES, while getEntries() returns $ENTRIES as is. Java code can call Color.getEntries() and treat the result as a java.util.List<Color>, as long as the Kotlin standard library is on its classpath. values() and valueOf() remain available to Java callers.

Exhaustive when over enums

Listing constants with entries and handling each one with when go together. When when has an enum subject, the compiler checks that every constant is covered. That's true for when used as an expression and, since Kotlin 1.7, for when used as a statement:

enum class Priority { LOW, MEDIUM, HIGH, CRITICAL }

fun slaHours(p: Priority): Int = when (p) {
    Priority.LOW -> 72
    Priority.MEDIUM -> 24
    Priority.HIGH -> 4
}
d3.kt:3:34: error: 'when' expression must be exhaustive. Add the 'CRITICAL' branch or an 'else' branch.
fun slaHours(p: Priority): Int = when (p) {
                                 ^^^^

The fix is to handle the new constant, not to add else. With else the compiler can't tell you about the next constant someone adds. If a few constants need no action, list them in an explicit empty branch:

enum class Priority { LOW, MEDIUM, HIGH, CRITICAL }

fun slaHours(p: Priority): Int = when (p) {
    Priority.LOW -> 72
    Priority.MEDIUM -> 24
    Priority.HIGH, Priority.CRITICAL -> 4
}

fun notify(p: Priority) {
    when (p) {
        Priority.HIGH, Priority.CRITICAL -> println("$p: page on-call")
        Priority.LOW, Priority.MEDIUM -> {}    // explicit: nothing to do
    }
}

fun main() {
    for (p in Priority.entries) {
        println("$p -> ${slaHours(p)}h")
    }
    Priority.entries.forEach(::notify)
}
LOW -> 72h
MEDIUM -> 24h
HIGH -> 4h
CRITICAL -> 4h
HIGH: page on-call
CRITICAL: page on-call

Iterating entries like this is also a simple test that a mapping function works for every constant. See When-statement with enums for more on when. When the cases need different data, use a sealed hierarchy instead of an enum; Sealed classes and interfaces compares the two.

Migrating from values() and enumValues()

The change is mechanical:

import kotlin.enums.enumEntries

enum class Role { GUEST, MEMBER, ADMIN }

// before
inline fun <reified T : Enum<T>> namesOld(): List<String> = enumValues<T>().map { it.name }
fun roleAtOld(i: Int): Role? = Role.values().getOrNull(i)

// after
inline fun <reified T : Enum<T>> names(): List<String> = enumEntries<T>().map { it.name }
fun roleAt(i: Int): Role? = Role.entries.getOrNull(i)

fun main() {
    println(namesOld<Role>() == names<Role>())
    println(roleAtOld(2) == roleAt(2))
    println(Role.entries.random() in Role.entries)
    // when you really need an array, e.g. for a Java API:
    val arr: Array<Role> = Role.entries.toTypedArray()
    println(arr.size)
}
true
true
true
3

Things to watch for:

Summary

Task Code
all constants Color.entries (a List<Color>, no allocation)
constant at an index Color.entries[i], Color.entries.getOrNull(i)
by exact name, throwing Color.valueOf("RED")
by name, safe Color.entries.firstOrNull { it.name == s }
by a property entries.associateBy { it.code } in the companion object
next constant entries[(ordinal + 1) % entries.size]
in generic code enumEntries<T>() with reified T : Enum<T>
generic valueOf enumValueOf<T>(name)
as an array Color.entries.toTypedArray()
from Java Color.getEntries()

Use entries everywhere you used values(). Keep values() only for Java code that needs an array.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents