Kotlin Enum

How to use Kotlin Enum classes

Understanding Kotlin Enum

By Patrick Luck

Introduction

The enum class was one of the features of Java that has been brought over to Kotlin. At their core, Kotlin enum classes are classes that are declared by using the enum keyword in front of the class keyword. Since kotlin enum classes are classes, they are free to include methods, attributes, and they can even implement interfaces.

Enums are best used when you need to group a set of constants together. By grouping the constants into a single type, you can pass the type of the enum as a method parameter or use it as a return type later on in the program. Since you now have the benefit of having compiler checks, you are less likely to experience bugs in your program plus the added benefit of improvement readability in your code.

Enums can be highly flexible since they allow you to have attributes on them as well as methods. Allowing enums to implement interfaces allows for polymorphism, so you can keep your code loosely coupled which helps to maintain code. You can also add additional properties to a kotlin enum class if you need to store more information about a constant. Let’s look at a few uses of kotlin enum classes to best understand how to use them.

Declaring a Kotlin Enum

Example Kotlin Enum

enum class FoodMenu {
    BURGER,
    CHICKEN,
    GYRO
}

Explanation

Let’s suppose we have a restaurant that serves food and the food on the menu will never change. We should certainly represent that food in some sort of a class, but since we know it’s going to be constant, we can use an enum for it. In our case, we have three constants, BURGER, CHICKEN, and GYRO. We are free to add other items to the menu later on should we choose to do so but for now, we will stick with just the three food items.

It is simple enough to declare a kotlin enum. All we need to do is use the keywords enum class followed by our curly braces and then a comma separated list of constants. In this way, the enum class in Kotlin isn’t much different than the ones we see in Java. As a matter of fact, this is one of the features of Java that become available after Java 1.5 and is still widely used today.

There is an immediate advantage to using the enum. Right away, whenever we see FoodMenu.GYRO in our code, we know that GYRO belongs to FoodMenu. Had we used a regular constant, we would see GYRO but there is no context for having GYRO in our code. Should another developer come in and read our code, they will know that GYRO belongs to FoodMenu thanks to the fact that it’s an enum.

Using kotlin enum as a parameter

fun printMenuItem(foodMenu : FoodMenu)

fun printMenuItem(foodMenu: FoodMenu){
    when(foodMenu){
        FoodMenu.BURGER -> println("Burger")
        FoodMenu.CHICKEN -> println("Chicken")
        FoodMenu.GYRO -> println("Gyro")
    }
}

fun main(args: Array){
    printMenuItem(FoodMenu.BURGER)
    printMenuItem(FoodMenu.GYRO)
}

Explanation

One of the main uses for a Kotlin enum class is to use it as a parameter of a method. In the above example, we have declared a function printMenuItem that takes a FoodMenu as a parameter. Inside of the body of the function is a kotlin when function call that acts like a switch statement and reacts accordingly. Since we used an enum as a parameter rather than a Long or a String, the compiler can check for us that all case statements are covered. Not only does this make the code more readable, but it also makes it more robust since if we add more food items later on to our kotlin enum class, the compiler will force use to either add an else branch to the kotlin when or add the new food item to it.

Later on in the code example, we call the printMenuItem function in the main function. As you can see from the code, we are passing in FoodMenu.BURGER and FoodMenu.GYRO into the parameter. Anyone who is reading this code will see that these constants are FoodMenu items and will understand the purpose of the constants.

Advanced Enums

PrintableFood and Displayable

interface Displayable {
    fun diplay()
}

enum class PrintableFood(val displayName : String) : Displayable {

    BURGER("Burger") {
        override fun diplay() = println(this.displayName)
    },
    CHICKEN ("Chicken Sandwich") {
        override fun diplay() = println("Printing ${this.displayName}")
    },
    GYRO ("Pork Gyro") {
        override fun diplay() = println("Getting a Greek ${this.displayName}")
    }
}

fun displayMenuItem(displayable: Displayable)
        = displayable.diplay()

fun main(args: Array){
    PrintableFood.values().forEach { it -> displayMenuItem(it) }
}

Explanation

As mentioned earlier, kotlin enum classes can have attributes and methods. This example starts with an interface Displayable that declares a display() method. Next we have a kotlin enum class that will implement the interface. You will notice that this class has a constructor that takes a String parameter and it also implements the Displayable interface.

Let’s start with the attribute first. Since this enum has a displayName property, it will have to initialize that property. We do that by adding a () after the name of the constant and passing a value to it. This is why you now see BURGER (“Burger”) rather than BURGER. Going forward, we can now call PrintableFood.BURGER.displayName and it will have the “Burger” String stored in that variable. We actually use the property when we implement the display() method in the class.

Just like in Java, a kotlin enum can implement an interface. However, each instance of the enum has to implement the interface, which is why we now have a class body after each declaration of the enum. This can allow for additional polymorphism in the class since each value in the enumeration isn’t forced to have the same implementation as the others.

Since PrintableFood implements Displayable, it can be used in any method that takes a Displayable variable. We see this in the main method where we go through each value in the PrintableFood enum and call displayMenuItem on it. Each value in PrintableFood will call the proper implementation of display() and print the correct value to the console.

Conclusion

Whenever you need to group constants together, you should consider using a kotlin enum. Doing so will make your code more readable and it will even offer protection against bugs through compiler checks. Since kotlin enum classes are just like any other class, they are free to declare attributes, methods, and even implement interfaces. For this reason, they are highly flexible and can be used to develop robust, readable, and loosely coupled code.

Enums also work great with kotlin when since the compiler will check and make sure that all cases of the enumeration are covered. This will help you maintain your code later on as you add values or remove them from your enum class. The kotlin compiler will force you to cover all cases of the enum or add an else block to it.

Github

You can get the code at https://github.com/archer920/Kotlin-Enum

You may also like

  1. Three uses for kotlin when
  2. Consuming REST with Spring and Kotlin
  3. Kotlin Scheduling Tasks with Spring Boot
  4. Kotlin Command Line Compile
  5. Kotlin String Formatting

Sources

  1. https://kotlinlang.org/docs/reference/enum-classes.html
  2. https://kotlinfrompython.wordpress.com/2017/10/16/enum/
  3. https://en.wikipedia.org/wiki/Enumerated_type
  4. http://www.codemag.com/Article/050104/Improve-Code-with-Enums
  5. https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html