如何在Kotlin中声明一个枚举类型的变量?

根据文档创建了一个枚举类

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

然后我试图在一些函数中声明一个变量

 val bitCount : BitCount = BitCount(32) 

但是有一个编译错误

如何声明一个BitCount类型的变量,并从Int初始化它?

错误:(18,29)Kotlin:枚举类型不能实例化

枚举实例只能在枚举类声明中声明。

如果你想创建新的BitCount,只需添加它,如下所示:

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

并在任何地方使用BitCount.x16

如其他答案中所述,您可以引用任何按名称存在的enum值,但不能构造一个新值。 这并不妨碍你做类似于你正在尝试的东西…

 // 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) 

如果您想要根据数值32找到enum的实例,则可以按照以下方式扫描值。 使用companion objectfrom()函数创建enum

 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 } } } 

然后调用函数来获得匹配的现有实例:

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

好漂亮 或者在这种情况下,您可以从数字中创建enum值的名称,因为两者之间具有可预测的关系,然后使用BitCount.valueOf() 。 这是伴随对象中新的from()函数。

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