Summarize of Kotlin Enum

6. Enum

1. Initialization

Enum classes as any other classes can have a constructor and be initialized

1
2
3
4
5
enum class Color (val rgb: Int){
RED(0xFF000),
GREEN(0x00FF00),
BLUE(0x0000FF)
}

2. Simple Enum

1
2
3
enum class Color2{
RED, GREEN, BLUE
}

Each enum constant is an object. Enum constants are separated with commas.

3. Mutability

Enums can be mutable, this is another way to obtain a singleton behavior:

1
2
3
4
5
6
enum class Color3(var x : Int = 0){
EARTH(7 * 10000),
MARS();

override fun toString(): String = "$name [x = $x]"
}
1
2
3
4
var c = Color3.MARS
println(c)
c.x = 1234
println(c)