Enum Classes in Kotlin

Ashish Tiwari
3 min readFeb 16, 2021

Why we use enum classes?

enum classes are used to increase the readability of your code by assigning pre-defined name to constants.enums are defined by adding the modifier enum in front of a class. Check fig1.1 for reference.

Fig 1.1

Some of the important points about enum classes are:

  • enum are data type that hold a set of constant.(From above example January,February,March and April are known as constants in enumeration).
  • Each enum constant is an object. Enum constant are separated by comma.
  • Each of the enum constant act as a separate instance of the class.
  • You can not create the instance of enum classes using constructor, hence we can say that enum classes are abstract, check Fig 1.2 for reference.
You can not create the instance of enum classes. (Fig 1.2)

If we are not able to create the instance of the enum classes then how are we going to extract the constant values?

This way you can initialize the enum classes in main function. (Fig 1.3)

More properties of enum classes

Fig 1.4
  1. values() it can return the constant in the form Array over which we can iterate to retrieve each constant.
  2. values().size values() return an array and values().size return the size of the array, from above example you can see the size of array is 4 because there are 4 constants.
  3. ordinal and name is used to fetch the position and name of the constant respectively.
  4. valuesOf() is used to get the enum constant using a string as argument.

You can also initialize the enum classes using primary constructor

Fig 1.5

Data type which is used as constructor is common in all the constant, for example in above picture string data type is common in all constant.

enums as Anonymous classes. Enum constants can behave as anonymous classes by implementing their own functions along with overriding base functions from the class as shown below.

Fig 1.6

enum inside an enum

Fig 1.7

In the next post we will discuss about sealed classes, there are some problems in enum classes which are addressed in sealed classes. Happy reading!!

--

--