07-20-2023, 04:06 PM
How would you rewrite the following Java code in Kotlin?
@SuppressWarnings({ "unchecked", "rawtypes" })
static Object getEnumValue(String enumClassName, String enumValue) throws ClassNotFoundException {
Class<Enum> enumClz = (Class<Enum>)Class.forName(enumClassName);
return Enum.valueOf(enumClz, enumValue);
}
The problematic line is `Enum.valueOf(enumClz, enumValue)`
The automatic conversion from IntelliJ IDE/Android Studio yields the following `Enum.valueOf<Enum>(enumClz, enumValue)`, however there's no such method `Enum.valueOf` in Kotlin.
Forcing Kotling to use `java.lang.Enum`: `java.lang.Enum.valueOf<Enum>(enumClz, enumValue)`. Compile error on the generic binding `One type argument expected for class Enum<E: Enum<E>>`.
Adding the type argument as `java.lang.Enum.valueOf<Enum<*>>(enumClz, enumValue)` yields a different error: `Type argument is not within its bounds. Expected: Enum<Enum<*>!>! Found: Enum<*>`.
@SuppressWarnings({ "unchecked", "rawtypes" })
static Object getEnumValue(String enumClassName, String enumValue) throws ClassNotFoundException {
Class<Enum> enumClz = (Class<Enum>)Class.forName(enumClassName);
return Enum.valueOf(enumClz, enumValue);
}
The problematic line is `Enum.valueOf(enumClz, enumValue)`
The automatic conversion from IntelliJ IDE/Android Studio yields the following `Enum.valueOf<Enum>(enumClz, enumValue)`, however there's no such method `Enum.valueOf` in Kotlin.
Forcing Kotling to use `java.lang.Enum`: `java.lang.Enum.valueOf<Enum>(enumClz, enumValue)`. Compile error on the generic binding `One type argument expected for class Enum<E: Enum<E>>`.
Adding the type argument as `java.lang.Enum.valueOf<Enum<*>>(enumClz, enumValue)` yields a different error: `Type argument is not within its bounds. Expected: Enum<Enum<*>!>! Found: Enum<*>`.