At runtime, I am trying to verify whether a particular KClass<out Any>
is an enum type or not.
What is the best way to do so? Can this be done without relying on a particular runtime (e.g., JVM or JS)?
fun isEnum( type: KClass<out Any> ): Boolean
{
... ?
}
In C#, we can check the specific type is enum or not by using the IsEnum property of the Type class. It will return true if the type is enum. Otherwise, this property will return false. It is a read-only property.
Kotlin enums are classes, which means that they can have one or more constructors. Thus, you can initialize enum constants by passing the values required to one of the valid constructors. This is possible because enum constants are nothing other than instances of the enum class itself.
Also a JVM-only solution, but a shorter one, using isSubClassOf
:
fun isEnum(type: KClass<out Any>) = type.isSubclassOf(Enum::class)
JVM specific
None of the solutions here where working for me (I had a KType
) so I came up with another approach. Here is a solution for converting the KClass
to a KType
and then checking if the KType
is an enum.
fun isEnum(kClass: KClass<out Any> ): Boolean {
val kType :KType = kClass::class.createType()
return (kType.javaType as Class<*>).isEnum
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With