简介:在Kotlin中,if - else 是一个表达式,即它会返回一个值,因此就不需要三元运算符。(作为表达式必须有else分支)
传统用法
var max: Int if (a > b) max = a else max = b 12345 12345表达式用法:
val max = if (a > b) a else b 1 1注:除常规使用方法外,常用in、is判断是否在某个区间,或者属于某个类型。
简介:when取代了C语言中的switch操作符,when 将它的参数和所有的分支条件顺序比较,直到某个分支满足条件
1、简单用法:
when (x) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { print("x is neither 1 nor 2") } } 1234567 12345672、如果很多分支需要相同的方式处理,则可以把多个分支条件放在一起,用逗号分隔:
when (x) { 0, 1 -> print("x == 0 or x == 1") else -> print("otherwise") } 1234 12343、可以用任意表达式(而不只是常量)作为分支条件
when (x) { parseInt(s) -> print("s encodes x") else -> print("s does not encode x") } 1234 12344、可以检测一个值在(in)或者不在(!in)某个区间或者集合
when (x) { in 1..10 -> print("x is in the range") !in 10..20 -> print("x is outside the range") else -> print("none of the above") } 12345 123455、检测一个值是(is)或者不是(!is)某个特定类型的值,由于智能转换,你可以访问该类型的方法和属性而需任何额外的检测。
val hasPrefix = when(x) { is String -> x.startsWith("prefix") else -> false } 1234 12341、遍历某个区间
for(i in 0..4)//为闭区间[0,4] print(i) 12 122、通过索引遍历一个数组或者一个 list,你可以这么做:
for (i in array.indices) print(array[i]) 12 123、库函数 withIndex :
for ((index, value) in array.withIndex()) { println("the element at $index is $value") } 123 123使用方法不变
return:默认从最直接包围它的函数或者匿名函数返回。 break:终止最直接包围它的循环。 continue:继续下一次最直接包围它的循环。
