关注 the documentation ,我创建了一个枚举类:
enum class BitCount public constructor(val value : Int)
{
x32(32),
x64(64)
}
然后,我尝试在某个函数中声明一个变量:
val bitCount : BitCount = BitCount(32)
但是有编译错误:
Error:(18, 29) Kotlin: Enum types cannot be instantiated
如何声明 BitCount 类型的变量并从 Int
对其进行初始化?
最佳答案
如其他答案所述,您可以引用按名称存在的 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 object
和 from()
函数创建 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")
https://stackoverflow.com/questions/31489386/
相关文章:
types - Kotlin:从列表(或其他功能转换)中消除空值
android - 在 Kotlin 中将接口(interface)作为参数传递
kotlin - 从 java 中调用作为 java 中关键字的 kotlin 函数?
android - 在 Android Studio 中创建 Kotlin 库
android - 如何通过 kotlin 中的 Intent 传递自定义对象
intellij-idea - Kotlin - IntelliJ 项目设置
android - 如何在 androidTest 范围内使用 kapt