Kotlin编程

Kotlin笔记(2):Control Flow

2017-01-13  本文已影响11人  yangweigbh

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返回的东西:

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一样

上一篇下一篇

猜你喜欢

热点阅读