Is there a way to do something idiotmatic in this ...
# codereview
c
Is there a way to do something idiotmatic in this case? I have a string value that can be an enum, and I basically want an exhaustive when on the enum == my string. In my head, something like this should work
Copy code
val buttonText = when (MyEnum.values() == myString) {
ONE -> "first case"
TWO -> "second case"
else -> "Your string does not match any of the enums"
}
Ooh. I think I got it.
Copy code
val buttonText = when (MyEnum.valueOf(myString)) {
ONE -> "first case"
TWO -> "second case"
else -> "Your string does not match any of the enums"
}
e
note,
valueOf
throws IAE on invalid input
c
OOoh. Good catch. Any way around that?
like. valueOfOrNull or something? (i can just google it, just talking out loud here)
e
there is no valueOfOrNull currently. it would be useful though https://youtrack.jetbrains.com/issue/KT-42619
it might be added via https://github.com/Kotlin/KEEP/blob/master/proposals/enum-entries.md after Kotlin 1.9 or thereabouts
Copy code
inline fun <reified T : kotlin.Enum<T>> safeValueOf(type: String?): T? {
    return java.lang.Enum.valueOf(T::class.java, type)
}
looks like i can add that
e
you have to wrap that in try-catch, the Java method also throws IAE
in which case you might as well
Copy code
try {
    MyEnum.valueOf(string)
} catch (_: IllegalArgumentException) {
    null
}
c
interesting...
hm
yeah. just gonna wrap it in a try/catch and set it to a variable on one line, then on another line I'll have my actual when statement with the else