Enum Classes in Kotlin

Topics Covered

Overview

Enum classes in Kotlin provide a very robust and easy way to define a set of named constants. These constants can have properties, functions, and behaviors as usual kotlin classes. While enum classes often serve as a means to encapsulate a set of constant values, Kotlin goes far beyond this basic role, offering a more powerful and dynamic feature set.

Introduction

Enum classes also known as Enumeration Class in Kotlin is a feature that allows us to define a class that stores a fixed set of values.

Although enum classes are usually used to have a named list of constant values, Kotlin enum class is much more powerful than that.

Unlike other programming languages, enum in Kotlin is not limited to a simple type or data structure. Instead, they can implement interfaces, have custom properties and methods, use anonymous classes, and so on. Enum in Kotlin makes the code easy to read and has less number of errors.

Some Important Points About Enum Classes in Kotlin

  • Enum Constants, Properties, and Methods:
    Enum class in Kotlin can not only have constants but also have methods and properties.
  • Instance-like behavior:
    Each enum constant can act as a separate instance which implies that we can access properties and call methods on individual constants of the enum class.
  • Readability Enhancement:
    Enum in Koltin enhances the readability of the code and is self-explanatory.
  • No Constructor Instantiation:
    Though we call it Enum classes, we are not allowed to create an instance or object of the Enum class using a constructor. Enum types cannot be instantiated.

Initializing Enums

Enum in Kotlin is initialized within the enum class. The syntax for the enum class is given below:

Enum in Kotlin can have a constructor that can be used to initialize the constant instances of the class. Note that we cannot create instances of an enum class outside of the enum class itself.

Enum constants are predefined and limited to the values you have explicitly defined within the enum class declaration. This restriction ensures that the set of valid values remains consistent and controlled.

Let us take an example of defining an enum class for different sizes of t-shirts:

Code:

Output:

Explanation:

Here, we are defining an enum class that stores the t-shirt sizes having two parameters abbreviation and description. We are defining four commonly used sizes as constants inside the class. These can be used to get the details in other classes and functions.

Enums Properties and Methods

Enum in Kotlin provides a few inbuilt properties and methods(static) to make programming easier for the developers. These can be accessed by any enum in Kotlin.

Properties of Enums:

  • ordinal:
    The constants inside the enum class are stored as we store elements in an array. These can be accessed with their index as well and we can use the ordinal property such as obj.ordinal to get the integer index or position in the enum declaration, starting from zero.
  • name:
    The name property in the enum class returns the name of the constant.

Methods of Enums:

  • values:
    The values method returns all constants defined in the enum declaration as a list.
  • valueOf:
    This method returns the enum constant with the given name.

Example to Demonstrate Enum Class in Kotlin

Let us look at an example to understand the use case of these methods and properties. Let the enum class be called Season and each instance of the season will have a list that contains a list of months.

Output:

Explanation:

In the example, above the values() method is used to get the list of the instances in the enum class Season. This list is then printed in the output as a key-value pair using the ordinal property that returns the index of the season and the name property that returns the name of the season.

Later we are using user input to match the available constants. The valueOf property takes a string and returns the object matching the name of the property. It throws an exception in case the object is not found. We are using valueOf to get the object and print the months of the season.

Enum Class Properties and Functions

Apart from built-in methods and properties, enum in Kotlin can have user-defined properties and functions as well. This lets us customize the behavior of the enum constants and add additional functionalities to it.

We can declare functions as usually, we usually define in normal classes using the fun keyword.

Example to Demonstrate Properties and Functions in Kotlin

Let us look at an example to understand user-defined properties and functions. Let us have a function called CoffeeType.

Code:

Output:

Explanation:

In the above example, the enum class coffeeType has two properties displayName and caffeineContent as well as two functions called brew() and getCaffeineInfo().

Enums as Anonymous Classes

Enums in Koltin can be defined as anonymous classes. Anonymous classes are typically used for creating single-use instances of classes that implement some interface or extend other classes without defining a new class explicitly.

On the other hand, enums are used to define constants of the same type associated with properties and methods. We can achieve anonymous behavior for our enum class in Kotlin.

Note:
Enum classes are not designed to be used anonymously. It's just this functionality can be achieved in Kotlin for some very special cases.

Let us see examples and usage of enum classes.

Usage of When Expression with Enum Class

The when expression is a very powerful tool in Kotlin used to switch on the variable value. It is used to handle different cases based on constants of enum. When used along with the enum constants, it can enable us to write clean and concise code and improve readability.

Let us look at an example of when expression with an enum class. We will take a class with months in a year and we will return several days in the respective month.

Code:

Output:

Explanation:

In this example, the getDaysInMonth() function uses the when expression to determine the number of days in the specified month based on the enum constant. The when expression in Kotlin is used for multiple conditional statements, similar to the switch statement. Enum stores the months and the expression stores the number of days in each of them. The function utilizes both the enum class and the function returns the number of days in a provided month.

Conclusion

  • Enum in Kotlin are very powerful and flexible classes that can store a set of named constants.
  • These constants have built-in properties name and ordinal which return the name and index of the constant respectively.
  • We can also have user-defined properties and functions for the enum class.
  • All the constants declared inside the enum class are its instances. We cannot create an instance of an enum class outside. Also, these can have constructors for the instance as normal Kotlin's classes.
  • We can use when expression along with enum class constants resulting in more organized and maintainable code.
  • For very rare cases, we can achieve anonymous behavior for our enum classes in Kotlin.