Kotlin Enum Classes

Kotlin Enum Classes

In programming, sometimes, there are only specific values of a type; to complete this, the concept of enumeration was introduced. Enumeration is a list of constants.

In Kotlin, like many other programming languages, Enum has its specific type, indicating some possible values. Kotlin enums are classes, unlike java classes.

There are some essential points about Enum Classes:

  • These constants are not just a collection of constants - they have advantages and methods
  • Each Enum constant acts as a specific class example and is separated by commas.
  • Enums increase the readability of your code by assigning predefined names to the constants.
  • An example of an Enum class cannot be created using constructors.
  • Enums are defined using the Enum keyword in front of the class.

Enum Initialization

Kotlin also has a constructor similar to Java items. Since enum constants are examples of an Enum class, constants can be started by transferring specific values to the primary constructor.

Properties and Methods of Enum

As in Java and other programming languages, Kotlin enum classes have built-in properties that programmers can use. Here are the key features and methods.


  • Ordinal: This property stores the ordinal value of the constant, which is usually an index based on zero.
  • Name: It stores the name of the constant.


  • Values: This method returns a list of all the constants defined in the enum class.
  • valueOf: These methods return the enum constant defined in the Enum and match the input string. If the constant is not in the Enum, an IllegalArgumentException is thrown.

Class Properties and Functions of Enum

From the enum class in Kotlin, a new type is defined. This class type may have its features and functions.

Properties can be given a default value; however, if not specified, each constant must define its value for the property.

In terms of functions, they are usually defined within companion objects, so they do not depend on the specific context of the class. However, it can be defined without companion objects.

Enum as Anonymous Classes

As well as overcoming the abstract functions of the class and implementing their functions, the constant also acts as an anonymous class. The most important thing is to override each Enum constant.

Use of when expression with enum class

A significant advantage of Kotlin's enum classes is that they work when combined with expression. Because enum classes limit the value that one type can take, when expressions and definitions are given for all constants, the need for other clauses is eliminated. Performing this task will generate a warning from the compiler.