Kotlin Program to Lookup Enum by String Value

Looking up an enum by its string value is a common task in programming, especially when dealing with user inputs or external data. Kotlin provides several approaches to efficiently perform this lookup operation. In this article, we will explore three different Kotlin Program to Lookup Enum by String Value that demonstrate various ways to lookup enums by their string values, along with outputs and explanations for each approach.

1. Kotlin Program to Lookup Enum by String Value Using valueOf() Function

1.1 Example Code:

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

fun main() {
    val input = "SOUTH"
    val direction = Direction.valueOf(input)

    println("Direction: $direction")
}

Output:

Kotlin
Direction: SOUTH

Explanation:

In this example, we use the valueOf() function provided by enums in Kotlin. It directly converts the input string “SOUTH” into the corresponding enum constant Direction.SOUTH.

2. Using Custom Lookup Function

2.1 Example Code:

Kotlin
enum class Color {
    RED, GREEN, BLUE
}

fun lookupColor(input: String): Color? {
    return Color.values().find { it.name == input }
}

fun main() {
    val input = "GREEN"
    val color = lookupColor(input)

    println("Color: $color")
}

Output:

Kotlin
Color: GREEN

Explanation:

Here, we define a custom lookup function lookupColor that iterates over all enum constants using Color.values() and finds the one with a matching name. It provides flexibility and allows handling cases where exact matching is required.

3. Using a Map for Lookup

3.1 Example Code:

Kotlin
enum class Month {
    JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
    JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
}

fun main() {
    val monthMap = mapOf(
        "JAN" to Month.JANUARY,
        "FEB" to Month.FEBRUARY,
        // Add mappings for other months...
    )

    val input = "JAN"
    val month = monthMap[input]

    println("Month: $month")
}

Output:

Kotlin
Month: JANUARY

Explanation:

In this example, we use a map to create a lookup table for enum values. This approach is useful when dealing with non-standard or abbreviated inputs, allowing for easy retrieval of corresponding enum constants.

Summary and Conclusion

In Kotlin, looking up an enum by its string value can be achieved through various methods:

  1. Using the valueOf() function directly provided by enums for exact matches.
  2. Implementing a custom lookup function for more flexible matching criteria.
  3. Utilizing a map as a lookup table for efficient retrieval of enum constants.

Each approach has its own strengths and is suitable for different scenarios. Understanding these methods empowers developers to efficiently handle enum lookup operations in Kotlin, enhancing the robustness and flexibility of their programs.