Trouble converting String to Enum with generics


#1

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?


#2

Yes, it was already reported as https://youtrack.jetbrains.com/issue/KT-11218, feel free to star or vote that issue to receive updates on it.


#3

Gar. Sorry I didn’t find that myself. To bad there isn’t something we can do ourselves about it.