美文网首页
Control Flow 控制流程

Control Flow 控制流程

作者: b7cda9616c52 | 来源:发表于2017-06-22 17:38 被阅读65次

If Expression If 表达式

Kotlin 中,if 是条件表达式,可返回值,没有三元操作符(condition ? then : else)。

传统的使用,判断 a < b

// Traditional usage 
var max = a 
if (a < b) max = b

else 结合使用:

// With else 
var max: Int
if (a > b) {
    max = a
} else {
    max = b
}

作为表达式使用:

// As expression 
val max = if (a > b) a else b

if 也可使用块:

val max = if (a > b) {
    print("Choose a")
    a
} else {
    print("Choose b")
    b
}

使用 if 作为表达式(如返回一个值或将其赋值为一个变量),必须有 else

查看 if 的语法 grammar for if ,如下:
if (used by atomicExpression)
: "if" "(" expression ")" controlStructureBody SEMI? ("else" controlStructureBody)? ;

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

if 很相像,当 x1 时,执行 print("x == 1"),当 x2 时,执行 print("x == 2"),如果 x 不等于 1 ,也不等于 2,则执行 else 里的 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 encodes x")
    else -> print("s does not encode x")
}

分支条件也可以是范围(range)内或范围外:

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

分支条件也可以是检查变量是否是某个类,因为 smart casts ,可以直接在后面使用该类型的方法和属性:

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

when 可以实现 if-else if

when {
    x.isOdd() -> print("x is odd")
    x.isEven() -> print("x is even")
    else -> print("x is funny")
}

when 的语法 grammar for when

For Loops For 循环

for 循环语法:
for (item in collection) print(item)

body 可以放在块里:

for (item: Int in ints) {
    // ...
}

循环过程中需要使用索引,循环如下:

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

也可以使用 withIndex 方法实现:

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

for 语法 grammar for for

While Loops While 循环

whiledo...while 与 Java 中的一样:

while (x > 0) {
    x--
}

do {
    val y = retrieveData()
} while (y != null) // y is visible here!

Break and continue in loops

Kotlin 支持循环中使用 breakcontinue,查看 Returns and jumps

相关文章

网友评论

      本文标题:Control Flow 控制流程

      本文链接:https://www.haomeiwen.com/subject/gxyfcxtx.html