Kotlin Enum

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

enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF)
}

Functions and Properties in enums

Enum classes can also declare members (i.e. properties and functions). A semicolon (;) must be placed between the last enum object and the first member declaration. If a member is abstract, the enum objects must implement it.
enum class Color {
RED {
override val rgb: Int = 0xFF0000
},
GREEN {
override val rgb: Int = 0x00FF00
},
BLUE {
override val rgb: Int = 0x0000FF
}
;
abstract val rgb: Int
fun colorString() = "#%06X".format(0xFFFFFF and rgb)
}

Simple enum

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

enum class Color {
RED, GREEN, BLUE
}

Mutability

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

enum class Planet(var population: Int = 0) {
EARTH(7 * 100000000),
MARS();
override fun toString() = "$name[population=$population]"
}

println(Planet.MARS) // MARS[population=0]
Planet.MARS.population = 3
println(Planet.MARS) // MARS[population=3]


Comments