In Kotlin, enumerations (enum class) allow you to declare a limited set of values and expand them with methods and properties.
enum class Direction { NORTH, SOUTH, WEST, EAST }
enum class Color(val rgb: Int) { RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF); fun containsRed() = (rgb and 0xFF0000 != 0) }
Color.RED.name), index (ordinal), and you can get the full list via values().== (identity) since elements are unique.Can you define an abstract method inside an enum class in Kotlin, as in Java, for each element to override it?
Correct answer: Yes, you can declare an abstract method in an enum style, and each element must provide its implementation!
enum class State { START { override fun next() = RUNNING }, RUNNING { override fun next() = STOPPED }, STOPPED { override fun next() = STOPPED }; abstract fun next(): State }
Story
When migrating from Java to Kotlin, the team attempted to inherit a new enum class like a regular class — it turned out that enums cannot be inherited, disrupting the architecture. They had to completely change their approach to the modularity of state machines.
Story
To store values in the database, they took the name of the element (
enum.name), but after refactoring, the enum elements were renamed — the data from the database became inconsistent with the new logic, leading to a loss of consistency (the storage value pattern was not implemented).
Story
When serializing an enum class via Gson, they forgot to include a custom TypeAdapter. In production, the service began to output incorrect JSON values because the standard parser serialized the wrong field (ordinal or name), and deserialization did not match between microservices.