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
Advertisements

Three uses for Kotlin When

Three uses for Kotlin When

Replace the if when

By Patrick Luck

Introduction

The kotlin when extension function is part of the Kotlin standard library and it is used to replace both the switch statement as well as the if-else statements. It is critical that you understand when to use the kotlin when function because when used properly, when can greatly increase the readability of your code. There are three primary different uses where using kotlin when is practical. The first case is comparing a value and then executing the proper branch of code when a true condition has been found. The second involves returning a value based on a try condition. Finally, when is also useful for exception handling.

Like switch and if-else, kotlin when allows you to specify a default case that will execute when none of the specified conditions have been found. A default case is optional as long as when is not being used to return a value. In other words, should you use the kotlin when function to return a value, you will be forced to include an else block in the function or the compiler will flag an error. However, as long as you are not returning a value by using kotlin when, you will not be required to have a default case. Let’s take a look at a few examples of using when in a real program.

Executing a block of code based on a condition

fun throwException(name : String)

fun throwException(name: String){
    when (name) {
        "RuntimeException" -> throw RuntimeException("RuntimeException")
        "IllegalArgumentException" -> throw IllegalArgumentException("IllegalArgumentException")
        "IndexOutOfBoundsException" -> throw IndexOutOfBoundsException("IndexOutOfBoundsException")
        else -> println("Not an exception")
    }

}

Explanation

Here is a function that throws an exception based on the name String parameter. In this case, we are using the kotlin when function to replace a switch or an if-else-else-if block. As you can see, the kotlin when function makes the code highly readable. We start by passing the name variable to when which allows the function to compare the value in name to the values listed on the left side of the ->. Our first value is “RuntimeException” so when name == “RuntimeException” the code to the right of the -> will execute and a RuntimeException is thrown.

The same logic holds true for the two other cases as well. When name == “IllegalArgumentException” the code to the right of -> next to “IllegalArgumentException” is executed and an IllegalArgumentException is thrown by the JVM. The same is also the case for “IndexOutOfBoundsException”.

Finally, we also have an else in this when function. The else acts like a default in a Java switch statement or as an else in an if block. In our case, when name isn’t “RuntimeException”, “IllegalArgumentException”, or “IndexOutOfBoundsException”, then the code to the right of the -> next to the else block executed and we print “Not an exception” to the console.

Exception Handling

fun handleException(name : String)

fun handleException(name : String){
    try {
        throwException(name)
    } catch (e : Exception){
        when (e) {
            is IllegalArgumentException -> println("Handling an IllegalArgumentException")
            is IndexOutOfBoundsException -> println("Handling an IndexOutOfBoundsException")
            is RuntimeException -> println("Handling a Runtime Exception")
        }
    }
}

Explanation

This is an example of when we are using the kotlin when function for exception handling. Developers who are familiar with Java will likely remember using multiple catch blocks for each kind of exception that they wanted to handle. Every kind of unique exception type had to have its own catch block until Java 7 when multi-catch handlers were introduced for when you wanted to use the same code to handle different exception types. However, using a unique catch block for every kind of or groups of exceptions was cumbersome and lead to a lot of boiler plate in your code.

Kotlin addressed this issue by allowing the when function to be combined with the is operator. Keep in mind that “is” is used to compare the type of an object with a class to see if object is of a specific type and return true or false accordingly. That means we have a boolean operation here which allows it to be used with when. For example, when e is IllegalArgumentException, we execute the code to the right of the -> and print “Handling an IllegalArgumentException”. Not only does this improve the readability of the code by allowing for a plain english construct, but we also do away with all of the catch blocks that we would have needed in Java.

Returning a value

fun returnFromWhen(name : String): Class?

fun returnFromWhen(name : String): Class? {
    return when(name){
        "RuntimeException" -> RuntimeException::class.java
        "IllegalArgumentException" -> IllegalArgumentException::class.java
        "IndexOutOfBoundsException" -> IndexOutOfBoundsException::class.java
        else -> {
            println("Returning a null value")
            null
        }
    }
}

Explanation

Our final case is for using when to return a value. This is a powerful construct because it allows us to avoid declaring intermediate variables in a function just for the purpose of returning a value. It also allows us to avoid multiple exit points in a function which many developers consider to be a bad practice since it can be prone to bugs.

Since when is a function, it can be combined with the return keyword to return a value. Should you decide to use this feature, you will need to keep in mind that the returning value needs to be the last statement in a block of code following the -> in each case of the when. The type of return value also had to be declared in the calling function as well, which is what we have in the function declaration.

The kotlin when function works the same as it does in the other two cases. We pass a variable to it and then compare it to the separate cases. The only difference is that the final statement in the code of the -> needs to be a return value of some sort. In our case, we are returning Class objects that extend from RuntimeException. Our function has also been declared as nullable so that we can return null. After each case in the when block, we return a Class object, except for the else case which returns null.

You will notice also that the else part has { } that wraps multiple statements. This can always be done with the kotlin when function and will allow you to execute a block of code when it is needed.

Conclusion

As you may have noticed, the kotlin when function is a great tool to use when you need to increase the readability of your code by allowing you to avoid if else statements. It is also more powerful than the Java switch statement, as you are free to use any boolean condition in the when statement. The most common patterns for using kotlin when is to execute a block of code, exception handling, and returning a value.

Many developers execute a block of code using kotlin when just as if they are using a Java switch statement. In this case, we are checking a value against different conditions and then acting accordingly. Using kotlin when in this fashion is more flexible than using a switch statement, because you are not limited to just numeric or String values. Kotlin when allows you to do any legal comparisons which makes it more powerful than a Java switch statement.

The kotlin when function is also used to avoid a messy list of catch blocks when you are handling exceptions. Instead, you can use the “is” operator to check the type of your exception object and respond as needed to the exception. This allows for more compact exception handling than what you can normally achieve in Java.

Finally, since kotlin when is a function, you can use it to return a value. This allows you to avoid having multiple exit points in your function and you can avoid needing to declare an unnecessary variable. Once again, this makes your code more concise and readable that what you can normally achieve in other programming languages.

Github

You can find the entire code for this post at https://github.com/archer920/Koltin-When-Exception

Sources

  1. https://kotlinlang.org/docs/reference/control-flow.html
  2. http://www.baeldung.com/kotlin-when
  3. https://www.programiz.com/kotlin-programming/when-expression
  4. https://antonioleiva.com/when-expression-kotlin/
  5. https://www.tutorialkart.com/kotlin/when-expression-in-kotlin/