Enum with abstract methods in Kotlin

Level 5251 keystrokes

An enum class can declare an abstract method that every constant implements in its own body. Each constant then behaves differently: ADD adds and MULTIPLY multiplies.

Kotlin code

// An enum whose constants each provide their own behavior
1enum class Operation {
// A constant with a body: implements apply as addition
2 ADD {
3 override fun apply(a: Int, b: Int) = a + b
4 },
// Implements apply as multiplication
5 MULTIPLY {
6 override fun apply(a: Int, b: Int) = a * b
// The ; after the last constant is required because members follow
7 };
8
// Abstract method that every constant must implement
9 abstract fun apply(a: Int, b: Int): Int
10}
11
// values() returns the constants in declaration order (entries is preferred since Kotlin 1.9)
12for (op in Operation.values()) {
// Prints ADD: 8, then MULTIPLY: 15
13 println("${op.name}: ${op.apply(5, 3)}")
14}

Output

ADD: 8
MULTIPLY: 15
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.

  • :× 8
  • (× 7
  • )× 7
  • {× 6
  • }× 6
  • ,× 5
  • .× 3
  • "× 2
  • =× 2
  • $× 2

More Kotlin examples at level 5

← Kotlin typing practice