Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
{
    ... ?
}
like image 492
Steven Jeuris Avatar asked Jul 02 '18 14:07

Steven Jeuris


People also ask

How do you know if a class is enum?

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.

What type is enum Kotlin?

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.


2 Answers

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

fun isEnum(type: KClass<out Any>) = type.isSubclassOf(Enum::class)
like image 135
zsmb13 Avatar answered Jan 03 '23 01:01

zsmb13


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
}
like image 42
Mike Rylander Avatar answered Jan 03 '23 01:01

Mike Rylander