I have variable unknownEnumClass: KClass<Enum<*>>
. How I can get their values?
I can not use kotlin.enumValues() function, because it has reified parameter.
In other words, I want to get a normal analog:
fun unknownEnumValues(unknownEnumClass: KClass<Enum<*>>): Array<Enum<*>> {
@Suppress("UNCHECKED_CAST")
return unknownEnumClass.java.getMethod("values").invoke(null) as Array<Enum<*>>
}
Maybe this is what you are looking for?
import kotlin.reflect.KClass
fun main(args: Array<String>) {
println("Vowels")
getEnumValues(Vowel::class).forEach { print("$it ") }
println()
println("Roman Numerals")
getEnumValues(RomanNumerals::class).forEach { print("$it ") }
}
//sampleStart
fun getEnumValues(enumClass: KClass<out Enum<*>>): Array<out Enum<*>> = enumClass.java.enumConstants
//sampleEnd
enum class Vowel { A, E, I, O, U }
enum class RomanNumerals { I, V, X, L, C, D, M }
3 Likes
SaclCastellon’s answer is a JVM specific one.
Since there is a multiplatform enumValueOf(value) method in the standard lib, is there a way to achieve the same thing (aka get an enum value from a KClass<E:Enum> and a string) in multiplatform code?