gpt4 book ai didi

enums - 如何在 Kotlin 中声明枚举类型的变量?

转载 作者:IT老高 更新时间:2023-10-28 13:29:02 32 4
gpt4 key购买 nike

关注 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 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")

关于enums - 如何在 Kotlin 中声明枚举类型的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31489386/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com