I have an enum with some instances Foo and Bar. If I have a string \"Foo\", how can I instantiate a Foo enum from that?
The default solution in Kotlin will throw an exception. If you want a reliable solution that works statically for all enums, try this!
Now just call valueOf. If the type is invalid, you'll get null and have to handle it, instead of an exception.
inline fun > valueOf(type: String): T? {
return try {
java.lang.Enum.valueOf(T::class.java, type)
} catch (e: Exception) {
null
}
}
Alternatively, you can set a default value, calling valueOf, and avoid a null response. You can extend your specific enum to have the default be automatic
inline fun > valueOf(type: String, default: T): T {
return try {
java.lang.Enum.valueOf(T::class.java, type)
} catch (e: Exception) {
default
}
}
Or if you want both, make the second:
inline fun > valueOf(type: String, default: T): T = valueOf(type) ?: default