Write a Kotlin Program to Lookup enum by String value

Kotlin is a statically typed programming language that runs on the Java Virtual Machine.

One of the language features of Kotlin is the ability to define an enumeration, which is a set of named values.

In this tutorial, we will discuss how to lookup an enum by its string value in Kotlin.

Assuming we have the following enumeration in Kotlin:

enum class Color {
    RED,
    GREEN,
    BLUE
}

If we want to lookup the Color enum by its string value, we can create a function that takes a string as input and returns the matching enum value. Here’s an example of such a function:

fun colorFromName(name: String): Color? {
    return try {
        Color.valueOf(name)
    } catch (e: IllegalArgumentException) {
        null
    }
}

In this function, we are using the valueOf() method of the Enum class to lookup the enum by its name.

The valueOf() method throws an IllegalArgumentException if the given name does not match any of the enum values, so we catch that exception and return null in that case.

Here’s an example of how to use this function:

val colorName = "RED"
val color = colorFromName(colorName)
if (color != null) {
    println("Color found: $color")
} else {
    println("Color not found for name: $colorName")
}

In this example, we are looking up the Color enum with the name “RED”. If the enum is found, we print a message with the enum value.

If the enum is not found, we print a message saying that the color was not found for the given name.

In conclusion, looking up an enum by its string value in Kotlin is easy using the valueOf() method of the Enum class.

By catching the IllegalArgumentException that may be thrown, we can return null when the given name does not match any of the enum values.