Kotlin Unleashed: when Expression

Well, I'm sure you already have it.

The warning we had in our first example becomes an error, which means the program does not compile anymore.

Let’s take our first example:fun myFunction(valueToTest: Any): Boolean { return when (valueToTest) { is MyType1 -> true is MyType2 -> true }}Here I added a return type to myFunction and the return keyword just before the when expression.

To make this code compile, we have to add the else case as we did to remove the warning:fun myFunction(valueToTest: Any): Boolean { return when (valueToTest) { is MyType1 -> true is MyType2 -> true else -> false }}This example compiles.

But I personally don't like much this kind of code.

By passing a parameter Any, we lose the killer feature this article is all about.

Killer feature, you said?Alright.

Let's add a bit more code to our example.

We need a sealed class or an enum class (behavior with when is the same):enum class MyEnum { CASE1, CASE2}MyEnum contains two cases, which by the way are Kotlin objects (singletons).

So we can have an exhaustive when without else case:fun myFunction(valueToTest: MyEnum): Boolean { return when (valueToTest) { CASE1 -> true CASE2 -> true }}Here it is!.This compiles perfectly.

But I know what you are wondering, why is this code pretty nice?.Well, it is all about maintaining it.

Imagine if a newbie developer arrives on the project we are working on.

If we ask him to add a new case, CASE3, what would happen?enum class MyEnum { CASE1, CASE2, CASE3}fun myFunction(valueToTest: MyEnum): Boolean { return when (valueToTest) { CASE1 -> true CASE2 -> true }}The code contained in myFunction would not compile anymore!.So our newbie knows in seconds where he needs to handle the new case he has just created.

An Android exampleIn this example, we will implement a sealed class which could help us to handle the different types of strings we can meet in Android.

A string can be a resource (which is of type Int and refers to a resource id) or a plain string.

sealed class AndroidString { data class Resource(val resource: Int) : AndroidString() data class Plain(val str: String) : AndroidString() fun toString(resources: Resources): String { return when (this) { is AndroidString.

Resource -> resources.

getString(resString) is AndroidString.

Plain -> str } }}And voilà!.This example shows how to create clean code with enums/sealed classes and the when expression.

In a near future, we could want to add another class to our AndroidString sealed class, for example to handle the plural strings case.

ConclusionWe’ve seen how useful the when expression can be to maintain way faster and easier applications.

This is a good way to avoid bugs when the programs we are working on grows, as long as we avoid as much as possible else cases so we can make the compiler show errors when needed.

Thanks for reading!.

. More details

Leave a Reply