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/

One thought on “Three uses for Kotlin When”

Leave a comment