How to create enum value from string value and class without exact generic value?

How can I convert this Java code (which is using raw classes) to Kotlin correctly?

public Enum getEnumValue(Class enumClass, String value) {
    return Enum.valueOf(enumClass, value);

When I try the following:

fun getEnumValue(enumClass: Class<Enum<*>>, value: String): Enum<*> =
        java.lang.Enum.valueOf(enumClass, value)

I get the warning

Type mismatch: inferred type is Enum<*>! but Enum<in Enum<*>!>! was expected

and with latest dev build the warning turns to compilation error…

I’m not able to replicate your warning or error, but maybe this code helps:

fun getEnumValue(enumClass: Class<Enum<*>>, value: String): Enum<*> =
    enumClass.enumConstants.first { == value }

Thanks, that helps to get rid of the warning. I am still wondering if there is a way to call java.lang.Enum.valueOf(class, name) with Kotlin generics (instead of raw classes in java) with a class where the enum type in generic is not known.

Do you need this function to receive any possible Class or only classes that are verified at compile time to be enums? I ask because your original Java code could receive e.g. Class<String>, but your Kotlin equivalent does not.

If enum requirement is fine, then I believe the proper solution is like this:

fun <T : Enum<T>> getEnumValue(enumClass: Class<T>, value: String): T {
    return java.lang.Enum.valueOf(enumClass, value)

But I’m not sure if this helps you match, because if you are using Class<Enum<*>> currently, then you will probably have exactly the same problem executing this above function as you have problem executing Enum.valueOf() right now.

Hi, no, I need it to receive any possible Class as you wrote, I cannot do <T : Enum<T>> - on the input I only have value type as KClass<*> and a String value - depending on a class it’s trying to convert the String value to appropriate type, e.g. Double, BigDecimal, Enum, ZonedDateTime…