Check if type is an Enum via Reflection

Hello friends,

I am building an offline tool and I need to scan our Data Classes for default values.

I need to dodge Enums though, so I need a way to check if a parameter is an Enum.
I have a class StarRating with an Enum called Shape inside of it.
When I check if this KParameter is an Enum like this:

val isEnum = param.type.javaClass.isEnum
the result is false

Is my approach incorrect?

This seems to work:
val isEnum = (param.type.classifier as KClass<*>).java.isEnum

I really hope Kotlin reflection gets some love…

1 Like

I don’t think there is anything wrong with the reflection API in this example. You probably assume only the simplest cases, but the language is much more complicated than that, so reflection has to be complex as well. Consider these examples:

fun test1(param: String) {}
fun test2(param: Color) {}
fun test3(param: Color?) {}
fun <T> test4(param: T) {}
fun <T : Color> test5(param: T) {}

enum class Color {
    RED, GREEN
}

In some cases it is not even clear whether we should consider a param to be enum or not, because it depends on the user specific needs (e.g. test3).

BTW, I suggest checking if classifier is KClass<*> instead of casting, because your code probably will crash in test4 and test5 cases.

1 Like