Search code examples
kotlingenericsenumscompanion-object

Kotlin Generic Function With Enum Constraint


I want to do something like the following:

inline fun<T: Enum<T>> myFunction(enumStr: String){
    T.valueOf(enumStr)
    //...
}

so that my generic parameter is constrained to be of enum class type so that I have access to the valueOf function. I am getting an error stating that:
Type parameter 'T' cannot have or inherit a companion object, so it cannot be on the left hand side of dot

which I understand to mean I can't use companion object functions on generics. Is there any way to achieve what I want - converting a string to a generic enum?


Solution

  • If you reify your type parameter, you can use the enumValueOf function (doc here). Like this:

    inline fun <reified T: Enum<T>> myFunction(enumStr: String) {
        val enumValue = enumValueOf<T>(enumStr)
        //...
    }