So I am trying to convert String to Enum via an inline reified extension function. The only problem is that type inference doesn’t work when the enum is nullable. Currently I have
inline fun <reified T: Enum<T>> String?.toEnumOrNull(): T? {
if (this == null) {
return null
}
return try {
enumValueOf<T>(this)
} catch (e: IllegalArgumentException) {
null
}
}
This works great when T is non null AKA not T?. But when it is T?, I have to specify the enum type.
val red: String? = "red"
val r1: Color = red.toEnum() // works
val r2: Color? = red.toEnumOrNull() // error
val r3: Color? = red.toEnumOrNull<Color>() // works
Has anyone else tried to do this?