How do I declare a variable of enum type in Kotlin?

As stated in other answers, you can reference any value of the enum that exists by name, but not construct a new one. That does not prevent you from doing something similar to what you were trying...

// wrong, it is a sealed hierarchy, you cannot create random instances
val bitCount : BitCount = BitCount(32)

// correct (assuming you add the code below)
val bitCount = BitCount.from(32)

If you were wanting to find the instance of the enum based on the numeric value 32 then you could scan the values in the following way. Create the enum with a companion object and a from() function:

enum class BitCount(val value : Int)
{
    x16(16),
    x32(32),
    x64(64);

    companion object {
        fun from(findValue: Int): BitCount = BitCount.values().first { it.value == findValue }
    }
}

Then call the function to get a matching existing instance:

val bits = BitCount.from(32) // results in BitCount.x32

Nice and pretty. Alternatively in this case you could create the name of the enum value from the number since you have a predictable relationship between the two, then use BitCount.valueOf(). Here is the new from() function within the companion object.

fun from(findValue: Int): BitCount = BitCount.valueOf("x$findValue")

Enum instances could be declared only inside enum class declaration.

If you want to create new BitCount just add it as shown below:

enum class BitCount public constructor(val value : Int)
{
    x16(16),
    x32(32),
    x64(64)
}

and use everywhere as BitCount.x16.

Tags:

Enums

Kotlin