Say I have an enum which is just
public enum Blah {
A, B, C, D
}
and I would like to find the enum value of a string, for example
Create an extension and then call valueOf
. If the type is invalid, you'll get null and have to handle it
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 avoiding 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