English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program to find enum by string value

Kotlin Comprehensive Examples

In this program, you will learn how to use the valueOf() method of enums to convert string values to enums in Kotlin.

Example: Find enum by string value

enum class TextStyle {
    BOLD, ITALICS, UNDERLINE, STRIKETHROUGH
}
fun main(args: Array<String>) {
    val style = "Bold"
    val textStyle = TextStyle.valueOf(style.toUpperCase())
    println(textStyle)
}

When running the program, the output is:

BOLD

In the above program, we have an enum class TextStyle, which represents the different styles a text block can have, such as bold, italic, underline, and strikethrough.

We still have a string named 'style' that contains the current style we want. However, not all of them are used.

Then, we use the valueOf() method of the enum TextStyle to pass the style and get the required enum value.

Since valueOf() takes a case-sensitive string value, we must use the toUpperCase() method to convert the given string to uppercase.

On the contrary, if we use:

TextStyle.valueOf(style)

This program will throw an exception No enum constant EnumString.TextStyle.Bold.

Here is the equivalent Java code:Java Program to Find Enum by String Value.

Kotlin Comprehensive Examples