kotlin中的when:强大的switch

参考网址
在Java(特别是Java 6)中,switch表达式有很多的限制。除了针对短类型,它基本不能干其他事情。
然而,Kotlin中when表达式能够干你想用switch干的每件事,甚至更多。
实际上,在你的代码中,你可以用when替换复杂的if/else语句。

kotlin的强大就是能够将复杂的或者冗长的代码 使用很简洁的方式达到同样的目的;


kotlin的when

1.像是java中的switch那样使用when,

when(条件){
  条件值1 -> 执行语句1
  条件值2 -> 执行语句2
  条件值3 -> 执行语句3
  else -> 执行语句4
}

2.自动转型(Auto-casting)

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

 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")
 }

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

3.无自变量的when

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

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

因when是表达式,所以它能够返回存储到变量里的值。
这里的无条件的when使用,还可以代替多条件的复杂if-elseif-else语句,添加多路径执行。这也是when的强大之处。

猜你喜欢

转载自blog.csdn.net/amethyst128/article/details/78204178
今日推荐