Steven Jeuris
Steven Jeuris

Reputation: 19130

How to check whether a type is an enum in Kotlin?

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
{
    ... ?
}

Upvotes: 9

Views: 8716

Answers (4)

Steven Jeuris
Steven Jeuris

Reputation: 19130

The following seems to work for JVM, relying on the qualified type name.

fun isEnum( type: KClass<out Any> ): Boolean
{
    return type.supertypes.any { t ->
        (t.classifier as KClass<out Any>).qualifiedName == "kotlin.Enum" }
}

However, this does not work for JS since KClass::supertypes is not available for that runtime.

Upvotes: 0

David Billings
David Billings

Reputation: 376

Somewhat late to the party but if you want to check if an Any object is an Enum you could do it with an extension function. Which makes your code cleaner if you don't want to get the class etc.

fun Any?.isEnum(): Boolean {
    return this != null && this::class.isSubclassOf(Enum::class)
}

Upvotes: 0

Rylander
Rylander

Reputation: 20179

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
}

Upvotes: 1

zsmb13
zsmb13

Reputation: 89628

Also a JVM-only solution, but a shorter one, using isSubClassOf:

fun isEnum(type: KClass<out Any>) = type.isSubclassOf(Enum::class)

Upvotes: 12

Related Questions