Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin enum with multiple "parameter"

Tags:

enums

kotlin

For an exercise I have an enum (set by the teacher) that looks like this :

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 ?

I have looked on the Internet for an answer but didn't find anywhere an enum with two "parameter" (don't know how to call it) so I start wondering if this enum is possible.

Thanks guys

like image 989
Playdric Avatar asked Nov 05 '18 18:11

Playdric


People also ask

Can an enum have multiple values?

The Enum constructor can accept multiple values.

Can enums have methods Kotlin?

Since Kotlin enums are classes, they can have their own properties, methods, and implement interfaces.


1 Answers

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.

like image 191
yole Avatar answered Oct 26 '22 14:10

yole