星空网 > 软件开发 > 操作系统

Kotlin中when表达式的使用:超强的switch(KAD 13)

作者:Antonio Leiva

时间:Feb 23, 2017

原文链接:https://antonioleiva.com/when-expression-kotlin/

Kotlin中when表达式的使用:超强的switch(KAD 13)images/loading.gif' data-original="http://images2015.cnblogs.com/blog/831804/201702/831804-20170226135723257-424361835.jpg" >

 

 

Java(特别是Java 6)中,switch表达式有很多的限制。除了针对短类型,它基本不能干其他事情。

 

然而,Kotlin中when表达式能够**想用switch干的每件事,甚至更多。

 

实际上,在你的代码中,你可以用when替换复杂的if/else语句。

 

Kotlin的when表达式

 

开始,你可以像switch那样使用when。例如,想象你有一个视图,基于视图可显示性显示提示。

 

你可以做:

 

1 when(view.visibility){2   View.VISIBLE -> toast("visible")3   View.INVISIBLE -> toast("invisible")4   else -> toast("gone")5 }

 

 

在when中,else同switch的default。这是你给出的当你的表达式没有覆盖情况下的解决方案。

 

不过when还有其它额外的特性,使其性能真正强大:

 

自动转型(Auto-casting)

 

如果检查表达式左边类型(如:一个对象是特定类型的实例),就会得到右边任意类型:

 

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

 

 

除类型检查外,when还能用保留字in检查一个范围或列表内的实例。

 

无自变量的when

 

通过该选项,我们可以检查在when条件左边想要的任何事:

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

 

因when是表达式,所以它能够返回存储到变量里的值。

 

Android应用的例子

 

前面的例子非常简单,但没有任何实际使用意义。

 

 

而这个我喜欢的例子是回答onOptionsItemSelected()。

1 override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {2   R.id.home -> consume { navigateToHome() }3   R.id.search -> consume { MenuItemCompat.expandActionView(item) }4   R.id.settings -> consume { navigateToSettings() }5   else -> super.onOptionsItemSelected(item)6 }

 

该consume函数是非常简单的执行操作并返回true。而我发现它对Android框架的一些方法非常有用。这类方法需要使用结果。

 

所涉及的代码非常简单:

 

1 inline fun consume(f: () -> Unit): Boolean {2   f()3   return true4 }

 

 

结论

 

 

通过when表达式,你能够非常容易地创建有几个行为路径的代码,而在这些位置上用原Java switch语句无法实现。

 

如果你要继续学习Kotlin,你可以获得免费指南学习怎样创建你的第一个项目,或获得这本书从头开始创建一个完整的APP。

 




原标题:Kotlin中when表达式的使用:超强的switch(KAD 13)

关键词:表达式

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流