Kotlin enumValues()

Kotlin enumValues()

In Kotlin, the enumValues() function is used to obtain an array of enum constants in the order they are declared.

This function is handy when you need to iterate over enum values dynamically.

Syntax

The syntax of the enumValues() function is:

inline fun <reified T : Enum<T>> enumValues(): Array<T>

The function returns an array of enum constants in the order they are declared.

Examples

1. Basic Usage of enumValues() function

In this example, we’ll use enumValues() to iterate over the constants of a simple enum.

Kotlin Program

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

fun main() {
    val directions = enumValues<Direction>()

    for (direction in directions) {
        println(direction)
    }
}

Output

NORTH
SOUTH
EAST
WEST

In this example, enumValues<Direction>() returns an array of Direction enum constants, and we iterate over them to print each direction.

Summary

In this tutorial, we’ve covered the Kotlin enumValues() function, its syntax, and how to use it to obtain an array of enum constants. This function is useful for dynamic enumeration handling, especially when the enum values need to be iterated or processed dynamically.