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 behavior1enum class Operation { // A constant with a body: implements apply as addition2 ADD {3 override fun apply(a: Int, b: Int) = a + b4 }, // Implements apply as multiplication5 MULTIPLY {6 override fun apply(a: Int, b: Int) = a * b // The ; after the last constant is required because members follow7 };8 // Abstract method that every constant must implement9 abstract fun apply(a: Int, b: Int): Int10}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: 1513 println("${op.name}: ${op.apply(5, 3)}")14}Output
ADD: 8 MULTIPLY: 15
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