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

综合编程 2017-02-24

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:

when(view.visibility){
    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:

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:

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) {
    R.id.home -> consume { navigateToHome() }
    R.id.search -> consume { MenuItemCompat.expandActionView(item) }
    R.id.settings -> 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 {
    f()
    return true
}

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 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

您可能感兴趣的

RxJava2系列之相较RxJava1的更新之处(二) 前言 通过本系列上一篇文章,我们了解了RxJava1中由于被观察者发送事件的速度远快于观察者处理事件的速度导致的背压问题,由此而生出背压策略。虽然RxJava1中有一些操作符支持背压策略,也有一些其他方法,但效果并不太理想。这个问题到了RxJava2中得到了更好地解决。本篇一起来看相较于RxJa...
Android颜色定义、设置、转换、拾取详解... Android中的颜色值通常遵循 RGB/ARGB 标准,使用时通常以 “ # ” 字符开头的8位16进制表示。其中 ARGB 依次代表透明度( Alpha )、红色( Red )、绿色( Green )、蓝色( Blue ),取值范围为 0 ~ 255 (即16进制的 0x00 ~ 0xff )...
Android判断是否快速点击新思路 背景需求 在用户提交表单内容,请求接口的通用场景下,增删改查 crud 操作是比较频繁出现的操作。 对于改查操作来讲,并不会引起数据上的问题,影响的最多是接口重复调用;但是对于增删操作来讲,很容易引起数据重复添加,删除异常等问题。 对用户来讲,网络延时或...
Binder总结分析_native层 上一篇文章: Binder总结分析_应用层 Binder架构在native层到底是如何实现的。本文是基于Gityuan大神的Binder系列—开篇系列文章简单总结的,如果想了解更多细节,请前往Gityuan大神博客。 我们就从添加服务和获取服务为例。 添加服务 /...
Java反射以及在Android中的特殊应用 反射的定义以及组成 关于反射,一般书上的定义是这样的:JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性;这种动态获取信息以及动态调用对象方法的功能称为java语言的反射机制,这几句解释说明了反射的作用,动态的跟类进行...
0
Antonio Leiva

责编内容来自:Antonio Leiva (本文源链)
阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。