ProgrammingKotlin Developer

Describe the enum class mechanism in Kotlin: what is an enum class, how does it differ from Java, what features and limitations does enum have, how to add your functionality, what nuances may arise during serialization and comparison. Provide an example.

Pass interviews with Hintsage AI assistant

Answer.

In Kotlin, enumerations (enum class) allow you to declare a limited set of values and expand them with methods and properties.

Key points:

  • An enum class is declared similarly to Java, but the syntax is stricter:
    enum class Direction { NORTH, SOUTH, WEST, EAST }
  • Enum elements are singletons, instances of the corresponding subtype of the class.
  • You can define additional properties and methods within an enum:
    enum class Color(val rgb: Int) { RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF); fun containsRed() = (rgb and 0xFF0000 != 0) }
  • Each value can be accessed by name (Color.RED.name), index (ordinal), and you can get the full list via values().
  • In Kotlin, you cannot inherit enum classes, but you can implement interfaces.
  • The difference from Java is that you cannot explicitly inherit classes from enum, and you cannot use nested lists;
  • Enums in Kotlin are not serialized by default using standard tools (e.g., Gson or Jackson) — special adapters/annotations are needed.

Comparing enums:

  • Enums are compared using == (identity) since elements are unique.
  • When serializing, names may change, so it is better to explicitly set values (storage value pattern).

Trick question.

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 }

Examples of real errors due to lack of knowledge of the topic.


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.