An enum is a Kotlin type whose instances are limited to named constants. Declare one with enum class, then use its constants to represent a fixed set of choices. section 2.3.1
Listing 2.9 Declaring a simple enum class
package ch02.colors
enum class Color {
RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET
}
Start with a compact Color enum: each named constant becomes an instance of the Color type. section 2.3.1
Enum constants can carry constructor arguments and expose properties or methods just like regular class instances. This makes a Color enum useful beyond naming values: each color can store red, green, and blue components, calculate an rgb value, and print itself. When an enum defines methods, a semicolon separates the constant list from the declarations that follow. section 2.3.1
Listing 2.10 Declaring an enum class with properties
package ch02.colors
enum class Color(
val r: Int, #1
val g: Int, #1
val b: Int #1
) {
RED(255, 0, 0), #2
ORANGE(255, 165, 0),
YELLOW(255, 255, 0),
GREEN(0, 255, 0),
BLUE(0, 0, 255),
INDIGO(75, 0, 130),
VIOLET(238, 130, 238); #3
val rgb = (r * 256 + g) * 256 + b #4
fun printColor() = println("$this is $rgb") #5
}
fun main() {
println(Color.BLUE.rgb)
// 255
Color.GREEN.printColor()
// GREEN is 65280
}
Inspect the expanded Color enum to see constructor parameters, per-constant values, a derived property, and an instance method together. section 2.3.1
Use a when expression to choose behavior for an enum value. Kotlin branches need no break statements, and several constants can share one branch by separating them with commas. For example, red, orange, and yellow can be grouped as warm colors, while green is neutral and blue, indigo, and violet are cold. Importing Color.* removes repeated qualifiers when the names remain unambiguous. section 2.3.2
Mnemonic from an enum
fun getMnemonic(color: Color) = when (color) { Color.RED -> "Richard"; Color.ORANGE -> "Of"; Color.YELLOW -> "York"; Color.GREEN -> "Gave"; Color.BLUE -> "Battle"; Color.INDIGO -> "In"; Color.VIOLET -> "Vain" } section 2.3.2






















