范围

使用in操作符检查数字是否在某个范围。

val x = 10
val y = 9
if (x in 1..y+1) {
    println("fits in range")
}

检查数字是否不再某个范围内。

val list = listOf("a", "b", "c")
if (-1 !in 0..list.lastIndex) {
    println("-1 is out of range")
}
if (list.size !in list.indices) {
    println("list size is out of valid list indices range too")
}

遍历范围。

for (x in 1..5) {
    print(x)
}

按照一定的步进。

for (x in 1..10 step 2) {
    print(x)
}
for (x in 9 downTo 0 step 3) {
    print(x)
}

results matching ""

    No results matching ""