Enum class in Kotlin

Level 3120 keystrokes

An enum class defines a fixed set of constants. Each constant has a name (its identifier as a String) and an ordinal (its 0-based position), and printing it shows its name.

Kotlin code

// Define three constants; their ordinals are 0, 1 and 2 in declaration order
1enum class Color { RED, GREEN, BLUE }
2
// Refer to a constant through the class name
3val color = Color.GREEN
// An enum's default toString() returns its name: prints GREEN
4println(color)
// name is the constant's identifier as a String: prints GREEN
5println(color.name)
// ordinal is the 0-based position: GREEN is second, so print 1
6println(color.ordinal)

Output

GREEN
GREEN
1
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • .× 3
  • (× 3
  • )× 3
  • ,× 2
  • {× 1
  • }× 1
  • =× 1

More Kotlin examples at level 3

← Kotlin typing practice