Enumeration valueOf() throws undeclared exceptions

These docs say:

The valueOf() method throws an IllegalArgumentException if the specified name does not match any of the enum constants defined in the class.

But my testing shows that on the Javascript platform, an IllegalStateException is thrown. On native platform (Windows), it throws kotlin.Exception.

Am I looking at the wrong documentation?

Just do:

fun <T : Enum<T>> T.valueOfOrNull(name: String) = 
    kotlin.runCatching { valueOf(name) }.getOrNull()

Then handle the null instead of a pesky exception.

Watch post below!

1 Like

It won’t work, because you need to call a static method, not a member function on some enum instance. To make it work you would write this:

inline fun <reified T : Enum<T>> enumValueOfOrNull(name: String): T? =
	runCatching { enumValueOf<T>(name) }.getOrNull()

You can follow the issue KT-35116 which tracks this bug.