P
P
pqgg7nwkd42018-05-20 22:13:56
Kotlin
pqgg7nwkd4, 2018-05-20 22:13:56

Kotlin: how to get a list of unknown Enum values?

In other words, how to implement the getEnumValues ​​function:

fun getEnumValues(enumClass: KClass<Enum<*>>): Array<Enum<*>>{
 ...
}

There is a built-in enumValues ​​function for this, but it has a reified parameter that cannot be passed such a parameter to.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pqgg7nwkd4, 2018-05-20
@pqgg7nwkd4

I couldn't think of anything better than this :(

fun KClass<out Enum<*>>.enumValues(): Array<Enum<*>> {
    @Suppress("UNCHECKED_CAST")
    return this.java.getMethod("values").invoke(null) as Array<Enum<*>>
}

G
GreyTeardrop, 2018-08-20
@GreyTeardrop

On the JVM, you can use java.lang.Class#getEnumConstants for this :
Under the hood, it uses the same reflection but caches the result.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question