The switch expression in Java, and especially in Java 6, are extremely limited. Apart from a very short amount of types, it can not be used for anything else.

But, however, when expressions in Kotlin can do everything you can do with a switch and much more.

Actually, with when you can substitute the most complex if/else you can have in your code.

when expression in Kotlin

For starters, you can use it as a regular switch. Imagine that, for example, you have a view and want to display a toast based on its visibility.

You can do:

In when, else is the same as default for switch. You give a solution for the rest of the alternatives you’re not covering in the expression

But when has some other extra features that make it really powerful:

Auto-casting

If you check something in the left side (for instance, that an object is an instance of an specific type), you’ll get the cast in the right side for free:

Besides checking a type, when can check for instance if an element is inside a range or a list, by using the reserved word in.

when without arguments

With this option, we can check basically anything we want in the left side of the when condition.

As when is an expression, it can return a value that can be stored in a variable.

An example applied to Android

The above examples are very simple and far from having any real use.

But an example that I like a lot is to consume the answer in an onOptionsItemSelected().

The consume function is a very simple one that executes the operation and returns true. I find it very useful for the methods of the Android framework that need to indicate if they have consumed the result.

The code involved is very simple:

Conclusion

With the when expression you can make it really easy to create code where you can specify the behaviour through several paths, and where the original Java switch lack some power.

If you want to continue learning about Kotlin, you can get the free guide to learn how to build your first project, or just get the book and create a complete App from scratch.

Author: Antonio Leiva

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.

Shares
%d bloggers like this: