Following the documentation, I created an enum class:
enum class BitCount public constructor(val value : Int) { x32(32), x64(64) }
Then, I'm trying to declare a variable in some function:
val bitCount : BitCount = BitCount(32)
But there is a compilation error:
Error:(18, 29) Kotlin: Enum types cannot be instantiated
How do I declare a variable of BitCount type and initialize it from an Int
?
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Initializing enums 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.
You can get the values in an enum using values() , which returns an Array<Types> in this case. You can use firstOrNull as a safe approach, or first if you prefer an exception over null. So add a companion object (which are static relative to the enum, so you can call Types. getByValue(1234) ( Types.
A change in the default value of an enum member will automatically assign incremental values to the other members sequentially. You can even assign different values to each member. The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong.
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")
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