常用方法:

fun main() {
    for(i in 0..3) {             // 0123 从0到3
        print(i)
    }
    print(" ")

    for(i in 0 until 3) {        // 012 从0到2(不包3)
        print(i)
    }
    print(" ")

    for(i in 2..8 step 2) {      // 2468 步进是2 
        print(i)
    }
    print(" ")

    for (i in 3 downTo 0) {      // 3210 倒数
        print(i)
    }
    print(" ")

}

一些另类用法:

for (c in 'a'..'d') {        // 1
    print(c)
}
print(" ")

for (c in 'z' downTo 's' step 2) { // 2
    print(c)
}
print(" ")

还可以用在if 判断上

val x = 2
if (x in 1..5) {            // 1
    print("x is in range from 1 to 5")
}
println()

if (x !in 6..10) {          // 2
    print("x is not in range from 6 to 10")
}

标签: for, range

评论已关闭