What does `valueOf()` do for an enum, and how does it behave when given an unknown name?
answer
- valueOf(name) -> constant by exact name
- inverse of the `name` property
- throws IllegalArgumentException on miss (not null)
- case-sensitive, ignores toString()
- safe: runCatching{enumValueOf<T>()}.getOrNull() or entries.firstOrNull
basics
~10 svalueOf("RED") looks up an enum constant by its exact name and returns it. If no constant has that name, it throws an IllegalArgumentException instead of returning null.
solid answer
~40 s`EnumType.valueOf(name: String)` is a synthetic static-like function that returns the constant whose `name` equals the argument exactly (case-sensitive). It is the inverse of the `name` property: `Color.valueOf("RED") === Color.RED`. On an unmatched name it **throws `IllegalArgumentException`**, not returns null — so for untrusted input (config, JSON, user data) wrap it in a try/catch or, more idiomatically, use `entries.firstOrNull { it.name == s }` or `enumValueOf<Color>(s)` / the reified `runCatching { enumValueOf<T>(s) }.getOrNull()`. Matching is exact and case-sensitive; "red" will not match RED. `valueOf` does a lookup, not a parse, so it ignores any overridden `toString()`. It pairs with `values()`/`entries` (which list all constants) to round-trip enums to and from their string names safely.
code
kotlin · 7 linesenum class Color { RED, GREEN, BLUE }
fun parseColor(s: String): Color? =
Color.entries.firstOrNull { it.name.equals(s, ignoreCase = true) }
println(parseColor("green")) // GREEN (tolerant)
// Color.valueOf("green") // would throw IllegalArgumentExceptiongo deeper
Knows valueOf returns the constant matching a name string.
Knows it throws IllegalArgumentException on a miss and is case-sensitive.
Provides safe parsing patterns (runCatching + enumValueOf, entries.firstOrNull) and the reified helper.
Defines deserialization contracts/error handling for enums across API boundaries and version skew.
## What `valueOf` does `valueOf` is a **synthetic companion-like function** generated for every enum. Called as `EnumType.valueOf(name)`, it returns the **single constant whose `name` exactly equals** the supplied String: ```kotlin enum class Color { RED, GREEN, BLUE } val c = Color.valueOf("GREEN") // Color.GREEN println(c === Color.GREEN) // true ``` It is the **inverse of the `name` property**: `Color.valueOf(x.name) === x` for any constant `x`. ## Exact, case-sensitive matching - The match is on the **declared identifier**, character for character, **case-sensitive**. - `Color.valueOf("green")` does **not** match `GREEN`. - It ignores any overridden `toString()` — it always looks up by `name`. ## Failure behavior — it throws This is the critical gotcha: when no constant matches, `valueOf` **throws `IllegalArgumentException`**; it does **not** return null. ```kotlin Color.valueOf("PURPLE") // throws IllegalArgumentException ``` So calling `valueOf` directly on **untrusted input** (HTTP params, config files, JSON) is a latent crash. Safer patterns: ```kotlin // 1) Reified top-level helper + runCatching val c1: Color? = runCatching { enumValueOf<Color>(input) }.getOrNull() // 2) Tolerant lookup over entries (also lets you normalize case) val c2: Color? = Color.entries.firstOrNull { it.name == input } val c3: Color? = Color.entries.firstOrNull { it.name.equals(input, ignoreCase = true) } ``` ## The reified free function Kotlin also offers a generic top-level function `enumValueOf<T>(name)` (and `enumValues<T>()`), useful in generic/`reified` code where you don't know the concrete enum at the call site: ```kotlin inline fun <reified T : Enum<T>> parse(s: String): T? = runCatching { enumValueOf<T>(s) }.getOrNull() ``` ## Round-tripping `valueOf` plus the `name` property (and `entries`/`values()` to enumerate) give you a clean, stable String round-trip — which is exactly why you serialize with `name`, not `ordinal`: ```kotlin val text = Color.RED.name // "RED" val back = Color.valueOf(text) // Color.RED ```
- What happens if the name doesn't match any constant?valueOf throws IllegalArgumentException. It never returns null, so wrap untrusted input in runCatching or use a firstOrNull lookup over entries.
- Is valueOf case-insensitive?No, it is exact and case-sensitive. For tolerant parsing, compare names yourself with equals(..., ignoreCase = true).
- How do you call valueOf when the enum type is a generic parameter?Use the reified top-level function enumValueOf<T>(name) inside an inline reified function.
saying these in an interview costs you the question
- Believing valueOf returns null on an unknown name
- Calling valueOf directly on user/JSON input without handling the exception
- Assuming valueOf is case-insensitive
- Thinking valueOf parses toString() output rather than name
- Not knowing about enumValueOf<T>/entries-based safe lookups