Kotlin js : hack to get the values of an unknown enum

Kotlin js is really experimental and does not allow a lot of things when it comes to reflect apis :

actually you can only read the class name or cast the value into a dynamic (javascript-like) object.

Ever wondered how to do call myEnum.values() in js without knowing the type ? Not permitted so far, but theorically possible if you are not afraid of getting your hands dirty.

1°) First of all, nest your enum class inside an object :

object Wrapper {
enum class MyEnum {VALUE_1, VALUE_2, VALUE_3, VALUE_4}

2°) Write that helper somewhere :

fun getEnumValuesOfClass(enumClass: String, parentClass: JsClass< *>) : List {
val parentClassJs : dynamic = js("new parentClass()")
val possibleEnum = parentClassJs[enumClass]
return if(js("possibleEnum||{}.values") != null)
(js("possibleEnum.values().map(function(x){return x.name$})") as Array
else listOf()

It can even be an extension function if you prefer : fun Enum.values … but you will have to pass the parent class still (I did not test with global, would it work ?)

3°) You are ready to get the list of enum values (as string)
getEnumValuesOfClass("MyEnum", Wrapper::class.js)

4°) Have fun.

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.