Kotlin example

How to convert a string to an enum in Kotlin

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Call Size.valueOf("MEDIUM"). It needs the exact constant name and throws IllegalArgumentException for anything else, so for input you don't control, search the constants instead: Size.entries.firstOrNull { it.name == text } returns a Size? that is null when nothing matches. Add ignoreCase = true to accept "medium", and put a fromKey() function in the enum's companion object to look up a custom value such as a code or a JSON key.

Every Kotlin enum class comes with valueOf(name), which turns a constant's name into the constant, and entries, a read-only list of all the constants in the order they are declared. There is no built-in valueOfOrNull, so the null-returning lookup is a one-line search over entries. The sections below cover both, input in the wrong case or with spaces, a reverse lookup by a custom value in a companion object (Kotlin's replacement for a static method), getting an enum from an Int, one generic helper for every enum, and how name and toString() differ, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1valueOf() and a lookup that returns nullRecommended

valueOf() compares the text with each constant's name, exactly and case-sensitively. When nothing matches it throws IllegalArgumentException, which suits names your own code wrote. For text from a user, a file or a URL, search entries with firstOrNull: the result is a nullable enum, so the compiler makes you handle the miss, usually with a default after ?:. entries arrived in Kotlin 1.9.0 and replaces values(), which still works but builds a new array on every call.

ValueOfLookup.kt
enum class Size { SMALL, MEDIUM, LARGE }

// Returns null instead of throwing when no name matches
fun sizeOrNull(name: String): Size? =
    Size.entries.firstOrNull { it.name == name }

fun main() {
    // valueOf() needs the exact constant name
    val size = Size.valueOf("MEDIUM")
    println(size)
    println(size == Size.MEDIUM)

    // Anything else throws IllegalArgumentException
    for (text in listOf("medium", "XL", "")) {
        try {
            println(Size.valueOf(text))
        } catch (e: IllegalArgumentException) {
            println(e.message)
        }
    }

    // entries: every constant, in declaration order
    println(Size.entries)

    // The null-returning lookup, with a default after ?:
    println(sizeOrNull("LARGE"))
    println(sizeOrNull("XL"))
    println(sizeOrNull("XL") ?: Size.MEDIUM)

    // A nullable String: ?.let skips the lookup for null
    val missing: String? = null
    println(missing?.let(::sizeOrNull))
}

Output

"MEDIUM" gives MEDIUM, and it is the same constant, so == prints true. The three misses show what valueOf() rejects: lower case gives No enum constant Size.medium, an unknown name gives No enum constant Size.XL, and the empty string gives No enum constant Size. with nothing after the dot. entries prints as a list, [SMALL, MEDIUM, LARGE]. The lookup returns LARGE for a match and null for XL, and the Elvis default turns that miss into MEDIUM. A null string never reaches the lookup and prints null. runCatching { Size.valueOf(text) }.getOrNull() gives the same result by catching the exception for you.

2Ignoring case, spaces and dashes

People type done, Done or in progress, while the constants are DONE and IN_PROGRESS. Either normalize the text before valueOf(), with trim() and uppercase(), or compare with name.equals(key, ignoreCase = true) inside the lookup. Kotlin's uppercase() doesn't depend on the machine's language settings, unlike Java's toUpperCase(), so it is safe for matching names. Map spaces and dashes to the underscore your constant names use.

IgnoreCase.kt
enum class Status { OPEN, IN_PROGRESS, DONE }

// Trim, turn spaces and dashes into underscores, ignore case
fun statusOf(text: String): Status? {
    val key = text.trim().replace(' ', '_').replace('-', '_')
    return Status.entries.firstOrNull {
        it.name.equals(key, ignoreCase = true)
    }
}

fun main() {
    // Normalize first, then valueOf()
    println(Status.valueOf("done".uppercase()))
    println(Status.valueOf(" open ".trim().uppercase()))

    // Or compare without case in the lookup
    val inputs = listOf(
        "open", "Done", "  DONE ", "in progress", "In-Progress", "closed",
    )
    for (input in inputs) {
        println("\"$input\" -> ${statusOf(input)}")
    }
}

Output

Both valueOf() calls succeed once the text is upper case and trimmed (DONE, OPEN). The lookup accepts every spelling in the list except the one that names no constant: " DONE " is trimmed, "in progress" and "In-Progress" both become IN_PROGRESS, and "closed" gives null. Without the trim(), " DONE " would miss too, because ignoreCase only ignores case.

3A reverse lookup in a companion object

Often the text isn't the constant's name at all: a JSON key such as read-only, a database code or a label. Give the enum a property for that value and add the lookup to its companion object. Kotlin has no static keyword; members of the companion are called on the class name, so Role.fromKey("admin") reads like a Java static method. entries.associateBy { it.key } builds a map once, the first time the enum is used, and every lookup after that is a map read. More on companions in how to create a static method.

CompanionLookup.kt
enum class Role(val key: String) {
    ADMIN("admin"),
    EDITOR("editor"),
    VIEWER("read-only");

    companion object {
        // Built once, the first time Role is used
        private val byKey = entries.associateBy { it.key }

        // Called on the class, like a Java static method
        fun fromKey(key: String): Role? = byKey[key]

        // A strict version with a clear message
        fun require(key: String): Role =
            fromKey(key) ?: throw IllegalArgumentException("Unknown role: $key")
    }
}

fun main() {
    println(Role.fromKey("read-only"))
    println(Role.fromKey("owner"))
    println(Role.fromKey("owner") ?: Role.VIEWER)

    // The other direction: the constant's own key
    println(Role.EDITOR.key)

    try {
        Role.require("owner")
    } catch (e: IllegalArgumentException) {
        println(e.message)
    }

    // valueOf() still uses the constant name, not the key
    println(Role.valueOf("VIEWER").key)
}

Output

fromKey("read-only") finds VIEWER, an unknown key gives null, and ?: falls back to VIEWER. Role.EDITOR.key goes the other way and prints editor. The strict version throws with its own message, Unknown role: owner, which is easier to trace in a log than valueOf()'s. The last line is the reminder that a custom property doesn't change valueOf(): it still wants VIEWER, not read-only. With only a handful of constants, entries.firstOrNull { it.key == key } inside fromKey works just as well; the map pays off for large enums or lookups in a hot loop.

4An enum from an Int: ordinal or a code

Every constant has an ordinal, its position in the declaration starting at 0, so entries[i] turns an index back into a constant, and entries.getOrNull(i) returns null instead of throwing for a bad one. Use the ordinal only for values that never leave the program. Saved in a database or sent over the network, it silently changes meaning the day someone adds or reorders a constant. For stored numbers, give each constant its own code and look it up with the same companion-object map as above.

EnumFromInt.kt
enum class Level(val code: Int) {
    LOW(10), MEDIUM(20), HIGH(30);

    companion object {
        private val byCode = entries.associateBy { it.code }

        fun fromCode(code: Int): Level? = byCode[code]
    }
}

fun main() {
    // ordinal is the position: 0, 1, 2
    println(Level.entries.map { it.ordinal })
    println(Level.entries[2])
    println(Level.entries.getOrNull(7))

    // entries[i] throws for an index that does not exist
    try {
        println(Level.entries[7])
    } catch (e: IndexOutOfBoundsException) {
        println(e.message)
    }

    // A code you choose survives reordering the constants
    println(Level.fromCode(20))
    println(Level.fromCode(25))
    println(Level.HIGH.code)
}

Output

The ordinals are [0, 1, 2], so entries[2] is HIGH. getOrNull(7) is null, while entries[7] throws IndexOutOfBoundsException with index: 7, size: 3. fromCode(20) finds MEDIUM and fromCode(25), a code no constant has, gives null. If you later insert a constant between LOW and MEDIUM, entries[1] means something new, but fromCode(20) still returns MEDIUM.

5One helper for every enum: enumValueOf<T>()

enumValueOf<T>(name) is valueOf() for a type parameter, and enumEntries<T>() (imported from kotlin.enums) is its entries. Both need T at run time, so they only work inside an inline function with a reified type parameter. That lets you write the null-returning, case-insensitive lookup once as an extension on String and use it with any enum. On older Kotlin versions without enumEntries, enumValues<T>() does the same job and returns an array.

GenericEnum.kt
import kotlin.enums.enumEntries

enum class Size { SMALL, MEDIUM, LARGE }
enum class Color { RED, GREEN, BLUE }

// reified: T is known at run time, so enumEntries<T>() works
inline fun <reified T : Enum<T>> String.toEnumOrNull(): T? =
    enumEntries<T>().firstOrNull { it.name.equals(this, ignoreCase = true) }

// The default value tells Kotlin which enum to parse
inline fun <reified T : Enum<T>> parseEnum(text: String, default: T): T =
    text.toEnumOrNull<T>() ?: default

fun main() {
    // Like valueOf(), but for a type parameter
    println(enumValueOf<Size>("LARGE"))

    println("green".toEnumOrNull<Color>())
    val size: Size? = "small".toEnumOrNull()
    println(size)
    println("purple".toEnumOrNull<Color>())

    println(parseEnum("blue", Color.RED))
    println(parseEnum("huge", Size.MEDIUM))

    // enumValueOf<T>() throws just like valueOf()
    try {
        enumValueOf<Color>("PURPLE")
    } catch (e: IllegalArgumentException) {
        println(e.message)
    }
}

Output

enumValueOf<Size>("LARGE") gives LARGE. The extension finds GREEN and SMALL in lower case and returns null for purple. In val size: Size? = "small".toEnumOrNull() the type comes from the variable, so the call needs no angle brackets; in parseEnum it comes from the default, which also covers the miss (huge gives MEDIUM). enumValueOf<T>() fails the same way as valueOf(), with No enum constant Color.PURPLE.

6name, toString() and the round trip

Going from an enum to a String is name, the constant exactly as declared. toString() returns the same text until you override it, and printing or a string template uses toString(). The trap: an overridden toString() changes what you print, but valueOf() still only accepts name. Store and send name (or your own key), and keep toString() for display.

NameAndToString.kt
enum class Fruit(private val label: String) {
    APPLE("Apple"),
    BLOOD_ORANGE("Blood orange");

    // Changes printing and string templates, not valueOf()
    override fun toString() = label
}

fun main() {
    val fruit = Fruit.BLOOD_ORANGE
    println(fruit)
    println("I like $fruit")
    println(fruit.name)

    // name round-trips through valueOf()
    println(Fruit.valueOf(fruit.name) == fruit)

    // toString() does not
    try {
        Fruit.valueOf(fruit.toString())
    } catch (e: IllegalArgumentException) {
        println(e.message)
    }

    // To parse the display text, search entries by it
    val picked = Fruit.entries.firstOrNull { it.toString() == "Apple" }
    println(picked?.name)
}

Output

Printing the constant and the template both use the override (Blood orange), while name is still BLOOD_ORANGE. Passing name back to valueOf() gives the same constant (true); passing the display text fails with No enum constant Fruit.Blood orange. To read display text back in, search entries by toString(), which finds APPLE.

7Which should you use?

MethodGivesOn no matchBest for
Size.entries.firstOrNull { it.name == text }Size?nullInput from users, files, URLs
Size.valueOf(text)SizeThrows IllegalArgumentExceptionNames your own code wrote
it.name.equals(text, ignoreCase = true)Size?nullTyped input in any case
Role.fromKey(key) in a companionRole?nullJSON keys, codes, labels
Level.entries.getOrNull(i)Level?nullIndexes inside one program only
text.toEnumOrNull<T>()T?nullOne helper for many enums
Size.values()Array<Size>New array each callAvoid: use entries

Frequently asked questions

Is there a valueOfOrNull for enums in Kotlin?

No. Neither Size.valueOfOrNull(text) nor enumValueOfOrNull<Size>(text) exists; both fail to compile with Unresolved reference. Write Size.entries.firstOrNull { it.name == text }, or runCatching { Size.valueOf(text) }.getOrNull(), which catches the exception for you. For many enums, use one reified helper built on enumEntries<T>().

What is the difference between entries and values() in Kotlin?

Both hold every constant in declaration order. values() returns a new Array on every call, so Size.values() === Size.values() is false, and an array can be changed. entries, added in Kotlin 1.9.0, is a read-only List created once, so Size.entries === Size.entries is true, and it has every list function such as firstOrNull and getOrNull. Use entries in new code.

What does "No enum constant" mean?

valueOf() found no constant with exactly that name. The message quotes the class and the text, for example No enum constant Size.medium for lower-case input, or No enum constant Size. (nothing after the dot) for an empty string. Fix the input with trim() and uppercase(), or switch to a lookup that returns null.

How do I convert an enum to a String in Kotlin?

Use name: Size.MEDIUM.name is "MEDIUM", and Size.valueOf(size.name) always gives the constant back. toString() and string templates return the same text unless the enum overrides toString(), in which case the result is for display only and valueOf() rejects it.

How do I call the companion lookup from Java?

From Kotlin it is Role.fromKey("admin"). From Java the same function is Role.Companion.fromKey("admin"). Add @JvmStatic to the function in the companion object and Java can call it as Role.fromKey("admin") too.

How do I use the parsed enum in a when expression?

Once you have a Status (not a Status?), a when that lists every constant needs no else branch, and the compiler reports an error if you add a constant and forget a branch. With a nullable result, handle null first, for example when (statusOf(text)) { null -> ...; Status.OPEN -> ... }, where null counts as one more case.

How does Gson turn a JSON string into an enum?

Gson matches the JSON value against the constant names, so {"size":"LARGE"} reads into a Size property. Unknown text, including "large" in the wrong case, becomes null rather than an error. To accept a different spelling, annotate the constant with @SerializedName("in_progress"); Gson then also writes that spelling.

Run it yourself

Open any of these in the full Kotlin editor to tweak, run and share.

Kotlin playground