0
0
Kotlinprogramming~5 mins

Enum entries iteration in Kotlin

Choose your learning style9 modes available
Introduction

Enums group related values together. Iterating enum entries helps you use all these values one by one.

You want to show all options in a menu made from enum values.
You need to check or process every enum value in a list.
You want to print all enum names for debugging or logging.
Syntax
Kotlin
enum class EnumName {
    ENTRY1,
    ENTRY2,
    ENTRY3
}

for (entry in EnumName.values()) {
    // use entry
}

EnumName.values() returns an array of all enum entries.

You can use a for loop to go through each entry.

Examples
This prints all colors in the Color enum.
Kotlin
enum class Color {
    RED, GREEN, BLUE
}

for (color in Color.values()) {
    println(color)
}
Prints each direction with a label.
Kotlin
enum class Direction {
    NORTH, EAST, SOUTH, WEST
}

for (direction in Direction.values()) {
    println("Direction: $direction")
}
If an enum has no entries, the loop runs zero times.
Kotlin
enum class EmptyEnum {
    // This enum has no entries
}

for (entry in EmptyEnum.values()) {
    println(entry)
}
Sample Program

This program prints all days of the week by iterating over the Day enum entries.

Kotlin
enum class Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

fun main() {
    println("Days of the week:")
    for (day in Day.values()) {
        println(day)
    }
}
OutputSuccess
Important Notes

Time complexity is O(n) where n is the number of enum entries.

Space complexity is O(n) because values() creates an array of all entries.

Common mistake: Trying to modify enum entries during iteration, which is not allowed.

Use iteration when you need to process all enum values. Use direct access when you only need one specific entry.

Summary

Enums group fixed related values.

Use EnumName.values() to get all entries.

Loop over entries to use or display all enum values.