美文网首页Kotlin编程
Kotlin笔记(2):Control Flow

Kotlin笔记(2):Control Flow

作者: yangweigbh | 来源:发表于2017-01-13 22:19 被阅读11次

    if

    Kotlin的if有返回值,返回值就是执行分支的最后一个表达式

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

    when

    when类似于switch, 如果是当做一个赋值语句的一部分,else是必须的

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

    条件可以写在一起

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

    is成立后会将变量自动转型:

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

    当when不带参数时,类似于if,会执行true后面的语句

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

    for

    for 用来遍历定义了iterator()的对象,iterator返回的东西:

    • next()方法
    • hasNext() return 布尔值

    for 还可以用来遍历具有index的对象

    for (i in array.indices) {
        print(array[i])
    }
    
    for ((index, value) in array.withIndex()) {
        println("the element at $index is $value")
    }
    

    while

    whiledo..while和Java一样

    相关文章

      网友评论

        本文标题:Kotlin笔记(2):Control Flow

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