控制&循环


If 语句

和java一样

    var str: String? = "01"
    var num: Int? = str as? Int
    if (num == null) {
        println("num =null")

    } else if (num == 1) {
        println("num == 1")

    } else {
        println("num =$num")
    }

for 循环

和java foreach类似 但是

    var l = listOf("A", "B", "C")
    for (letter in l) {
        println("The current letter is $letter")
    }

如果想拿到序号,实现如下

 for ((index, value) in l.withIndex()) {
        println("This index is $index and value is $value")
 }

总输出:

The current letter is A
The current letter is B
The current letter is C
This index is 0 and value is A
This index is 1 and value is B
This index is 2 and value is C

while & do while循环

和java 一样

    var list = listOf<String>("What", "are", "fuck", "!")
    var index = 0
    do {
        println("Do while: The index=$index and letter is ${list[index]}")
        index++
    } while (index < list.size)

    index = 0
    while (index < list.size) {
        println("While: The index=$index and letter is ${list[index]}")
        index++
    }

输出:

/**
Do while: The index=0 and letter is What
Do while: The index=1 and letter is are
Do while: The index=2 and letter is fuck
Do while: The index=3 and letter is !
While: The index=0 and letter is What
While: The index=1 and letter is are
While: The index=2 and letter is fuck
While: The index=3 and letter is !
*/

when 表达式

在kotlin 中没有swith 选择语句 只有when

fun whenTest(num: Int) {
    when (num) {
        1 -> println("This num is one.")
        2 -> println("This num is Two.")
        else -> println("Let us go now,man!")
    }
}
 whenTest(2)//This num is Two.

可以看出,这和java中的swith 有很多相似之处,但是when 的功能更为强大,可以接受任何类型的对象,而swith 只有有限的几个类型。

results matching ""

    No results matching ""