Kotlin控制流

2017-06-22  本文已影响0人  李庆雪

表达式和语句的区别:

If表达式

在 Kotlin 中, if 是一个表达式,即它会返回一个值。 因此就不需要三元运算符(条件 ? 然后 : 否则),因为普通的 if 就能胜任这个角色。

    // 传统用法
    var max = a
    if (a < b) max = b
    // With else
    var max: Int
    if (a > b) {
        max = a
    } else {
        max = b
    }
    // 作为表达式
    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 分支。


When 表达式

when 取代了java 语言的 switch。其最简单的形式如下:

when (x) {
        1 -> print("x == 1")
        2 -> print("x == 2")
        else -> { // 注意这个块
            print("x is neither 1 nor 2")
        }
    }

when将它的参数和所有的分支条件顺序比较,直到某个分支满足条件。 when 既可以做表达式也可以做语句使用。如果它做表达式, 符合条件的分支的值就是整个表达式的值,如果当做语句使用, 则忽略个别分支的值.
如果其他分支都不满足条件将会求值 else 分支。 如果 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")
    }
    when (x) {
        in 1..10 -> print("x在范围内")
        in validNumbers -> print("x有效")
        !in 10..20 -> print("x在范围外")
        else -> print("以上都不是")
    }
    fun hasPrefix(x: Any) = when(x) {
        is String -> x.startsWith("prefix")
        else -> false
    }
    when {
        x.isOdd() -> print("x is odd")
        x.isEven() -> print("x is even")
        else -> print("x is funny")
    }
For 循环

for 循环可以对任何提供迭代器(iterator)的对象进行遍历,语法如下:
for (item in collection) print(item)
循环体可以是一个代码块。

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

如上所述, for 可以循环遍历任何提供了迭代器的对象。即:
有一个成员函数或者扩展函数 iterator() ,它的返回类型
有一个成员函数或者扩展函数 next() ,并且
有一个成员函数或者扩展函数 hasNext() 返回 Boolean 。
这三个函数都需要标记为 operator 。
对数组的 for 循环会被编译为并不创建迭代器的基于索引的循环。
如果你想要通过索引遍历一个数组或者一个 list,你可以这么做:

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

注意这种“在区间上遍历”会编译成优化的实现而不会创建额外对象。
或者你可以用库函数 withIndex

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

while 和 do .. while 照常使用

    while (x > 0) {
        x--
    }
    do {
        val y = retrieveData()
    } while (y != null) // y 在此处可见
返回与跳转(Returns and Jumps)

Kotlin支持三种跳转操作符

break和continue标签(Break and Continue Labels)

Kotlin中的任何表达式都可以用标签标记,标签是后面加@符号的标识符的形式,例如:abc @,fooBar @

loop@ for (i in 1..100){ // loop@就是标签
    //...
}

使用break 跳转到标签处,跳出循环

loop@ for (i in 1..10) {
    for (j in i..10) {
        if (j == 5) 
            break@loop // 跳出循环
        Log.e(Tag, j.toString()) // j 为5的时候跳出了循环,只打印1、2、3、4
    }
}

使用continue跳转到标签处,进行下一次循环

loop@ for (i in 1..10) {
    for (j in i..10) {
        if (j == 5) 
            continue@loop // 跳出本次循环,进行下一次循环
        Log.e(Tag, j.toString()) // j 为5的时候跳出了循环,所有不会打印5
    }
}

return标签(Return at Labels)
在字面函数,局部函数,以及对象表达式中,函数可以在 Kotlin 中被包裹。return允许返回到外层函数。

fun foo() {
    ints.forEach {
        if (it == 0) return // 跳出forEach
        print(it)
    }
}

return表达式返回到最近的闭合函数(foo())

fun foo() {
    ints.forEach lit@ {
        it (it ==0) return@lit 
        // 这样就不会return到foo函数,而是return到标签处的forEach函数
        print(it)
    }
}

通常这种情况用一种更方便的标签,例如用一个和传入的 Lambda 表达式名字相同的标签。

fun foo() {
    ints.forEach {
        if (it ==0) return@forEach 
        // 与上面一样,return到标签处的forEach函数
        print(it)
    }
}

另外,可以用匿名函数替换lambda表达式,使用 return 语句可以从匿名函数中返回

fun foo() {
    ints.forEach(fun(value:  Int){
        if (value == 0) return
        print(value)
    })
}

当要返一个回值的时候,解析器优先选用标签限制的 return,即
return@a 1
意为“从标签 @a 返回 1”,而不是“返回一个标签标注的表达式 (@a 1) ”。

上一篇 下一篇

猜你喜欢

热点阅读