Using “when” expression in Kotlin: The “switch” with super powers (KAD 13)

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.

Would you like to start today to take the next step? I recommend that you sign up to my free training here.

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:

    View.VISIBLE -> toast("visible")
    View.INVISIBLE -> toast("invisible")
    else -> toast("gone")

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:


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:

when (view) {
    is TextView -> toast(view.text)
    is RecyclerView -> toast("Item count = ${view.adapter.itemCount}")
    is SearchView -> toast("Current query: ${view.query}")
    else -> toast("View type not supported")

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.

val res = when {
    x in 1..10 -> "cheap"
    s.contains("hello") -> "it's a welcome!"
    v is ViewGroup -> "child count: ${v.getChildCount()}"
    else -> ""

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().

override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { -> consume { navigateToHome() } -> consume { MenuItemCompat.expandActionView(item) } -> consume { navigateToSettings() }
    else -> super.onOptionsItemSelected(item)

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:

inline fun consume(f: () -> Unit): Boolean {
    return true


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.

And if you want to learn how to use Kotlin to develop your own Android Apps, I recommend you take a look at my free training. Reserve your place!

6 thoughts on “Using “when” expression in Kotlin: The “switch” with super powers (KAD 13)”

  1. It is worth noting one small difference between the Java switch and Kotlin’s when. In a Java switch if you don’t use break in a case then you will get fall through and another case may also get run. If I understand when correctly then fall through is not possible, only the first match will ever get run.

  2. What if we use ranges in each Kotlin “case” that overlap each other? Would it run all true blocks? If yes, that could help on stuff like running database updates in Android by oldVersion in range. It would look like something like this:

    1 -> // run update to 2
    in 1..2 -> // run update to 3
    in 1..3 -> // run update to 4

    1. No, when one branch of “when” is executed, the “when” expression finishes. Consider it like an “if/else” (it’s essentially what it’s using at bytecode level)

Comments are closed.