Parsing strings to arbitrary enums in Kotlin Multiplatform

I was wondering whether it’s possible to implement a function such as the following in Kotlin Multiplatform:

inline fun <reified T : Enum<T>> parseToEnum(value: String): T {
    // ?

Basically, a function that takes the type of an Enum and a string and then returns the enum value of enum T that matches the passed string ( value ).

I know that it is possible in Java (and therefore in Kotlin/JVM) but I fear that there might not be a way to do this in common multiplatform code, because there’s very little reflection data retained at runtime.

If there’s a way to do this (or something similar in functionality), please let me know.

Using Kotlin 1.5.20 (or generally the newest version, I can update if necessary)

It already exists! enumValueOf

1 Like

Thank you so much! I really thought it wouldn’t be possible. Funny how I basically wrote same signature for a “hypothetical function” :sweat_smile:

1 Like

I actually have to come back to this, because I figured out that for my use case, having a inline fun with reified typearg is really just useful at the outermost scope. I’m running into a lot of problems with making all functions down the callstack inline… Is there a way to do it with a KClass instead?


1 Like