对于一个练习,我有一个枚举(由老师设置),如下所示:

enum class Weapon(name: String, damage: Int) {
    SWORD("Sword", 12),
    AXE("Axe", 13),
    BOW("Bow", 14)
}

The weapon will be an attribute of a data class Player
But once I set player.weapon = Weapon.SWORD
How do i access to the name or damage of the weapon ?

我在互联网上寻找答案,但没有找到任何带有两个"参数"的枚举(不知道如何称呼它),所以我开始怀疑这个枚举是否可行.

Thanks guys

推荐答案

As shown in the documentation, you need to declare the name and damage as properties of the enum class, using the val keyword:

enum class Weapon(val weaponName: String, val damage: Int)

Then you'll be able to simply access player.weapon.weaponName.

Kotlin相关问答推荐

Kotlin—从列表中枚举属性计算不同值的数量

我可以在kotlin/java.util.scanner中跳过分隔符而不重复吗?

如何创建一个空的kotlin工作?

Kotlin 中命名构造函数的惯用方式

如何优雅地声明一个StateFlow?

扩展属性委托给实例属性

使用调度程序运行异步 Kotlin 代码

如何使用 Firebase 和 Kotlin 在文本 (Jetpack Compose) 中显示当前用户名?

Kotlin 协程按顺序执行,但仅在生产机器上执行

Kotlin:使用另一个列表和字母顺序对列表进行排序的有效方法

为什么在 Kotlin 中调用私有构造函数会导致错误为无法访问 是什么?

Kotlin 日期格式从一种更改为另一种

为什么 Kotlin 扩展运算符在传递原始可变参数时需要 toTypedArray()?

requireNotNull vs sure !! 操作符

Kotlin suspend fun

ObserveForver是否了解生命周期?

是否在Kotlin中重写enum toString()?

Kotlin 与 C# 中的标志枚举变量具有相似效果的方式是什么

具有多个 parameter的 Kotlin 枚举

如何在 Fragment 中使用 Anko DSL?