Kotlin流程控制

if , when , for , while

if 表达式

在 Kotlin 中,if 是带有返回值的表达式。因此Kotlin没有三元运算符(condition ? then : else),因为 if 语句可以做到同样的事。

// 传统用法
var max = a
if (a < b) max = b
// 带 else
var max: Int
if (a > b) {
    max = a
}
else{
    max = b
}
// 作为表达式
val max = if (a > b) a else b

When 表达式

when 取代了 C 风格语言的 switch 。最简单的用法像下面这样

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x is neither 1 nor 2")
    }
}

注:如果把 when 做为表达式的话 else 分支是强制的
如果有分支可以用同样的方式处理的话,分支条件可以连在一起

when (x) {
    0,1 -> print("x == 0 or x == 1")
    else -> print("otherwise")
}

可以用任意表达式作为分支的条件

when (x) {
    parseInt(s) -> print("s encode x")
    else -> print("s does not encode x")
}

is in

in 或者 !in 检查值是否值在一个范围或一个集合中

when (x) {
    in 1..10 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    !in 10..20 -> print("x is outside the range")
    else -> print("none of the above")
}

is 或者 !is 来判断值是否是某个类型。

val hasPrefix = when (x) {
    is String -> x.startsWith("prefix")
    else -> false
}

for 循环

for 循环可以对所有提供迭代器的变量进行迭代。等同于 C# 等语言中的 foreach。语法形式

 for (item in 1..10)
        println(item)

for (i in array.indices)
    print(array[i])

while 循环

while 和 do...while 和其它语言没什么区别

while (x > 0) {
    x--
}

do {
    val y = retrieveData()
} while (y != null) // y 在这是可见的

在循环中使用 break 和 continue

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容