zoukankan      html  css  js  c++  java
  • Kotlin中when表达式的使用:超强的switch(KAD 13)

    作者:Antonio Leiva

    时间:Feb 23, 2017

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

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

    然而,Kotlinwhen表达式能够干你想用switch干的每件事,甚至更多。

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

    Kotlinwhen表达式

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

    你可以做:

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

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

    不过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 true
    4 }

    结论

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

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

  • 相关阅读:
    团队项目-典型用户及用户场景分析
    课堂小练习-找“水王”
    课堂小练习—电梯
    团队项目—用户需求调研报告
    课堂小练习
    团队项目的NABC
    梦断代码—随笔三
    梦断代码—随笔二
    结对开发5_循环二维数组最大字数组
    结对开发4_循环数组的最大值
  • 原文地址:https://www.cnblogs.com/figozhg/p/6444312.html
Copyright © 2011-2022 走看看