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.

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.

Puedes hacer:

    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.

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

overridefunonOptionsItemSelected(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:

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

If you want to continue learning about Kotlin, you canget the free guide to learn how to build your first project, or justget 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.

Twitter Google+ Linkedin Github

稿源:Antonio Leiva (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Using “when” expression in Kotlin: The “switch” with super powers (KAD 13)

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录