Kotlin enumValueOf()

Kotlin enumValueOf()

In Kotlin, the enumValueOf() function is used to obtain an enum constant by its name.

This function is useful when you need to get an enum constant based on a string representation.

In this tutorial, we shall learn the syntax and go through some examples of Kotlin enumValueOf() function.

Syntax

The syntax of the enumValueOf() function is:

inline fun <reified T : Enum<T>> enumValueOf(name: String): T

where

ParameterDescription
nameThe name of the enum entry.
Parameter of enumValueOf() function

The function returns the enum constant with the specified name.

Examples

1. Basic Usage of enumValueOf() function

In this example, we’ll use enumValueOf() to obtain an enum constant by its name.

Kotlin Program

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

fun main() {
    val direction = enumValueOf<Direction>("NORTH")
    println("The selected direction is: $direction")
}

Output

The selected direction is: NORTH

In this example, enumValueOf<Direction>("NORTH") returns the enum constant with the name “NORTH,” and we print the selected direction.

2. Handling IllegalArgumentException

If the specified name does not match any enum constant, the enumValueOf() function throws an IllegalArgumentException.

Kotlin Program

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

fun main() {
    try {
        val invalidDirection = enumValueOf<Direction>("UNKNOWN")
        println("Selected direction: $invalidDirection")
    } catch (e: IllegalArgumentException) {
        println("Error: ${e.message}")
    }
}

Output

Error: No enum constant Direction.UNKNOWN

In this example, attempting to get an enum constant with the name “UNKNOWN” results in an IllegalArgumentException, and we handle the exception by printing an error message.

Summary

In this tutorial, we’ve covered the Kotlin enumValueOf() function, its syntax, and how to use it to obtain an enum constant by its name. Remember to handle the IllegalArgumentException when using this function to prevent runtime errors.