kotlin的for循环遍历

kotlin的for循环遍历

 

1、List

    val list = listOf("A", "B", "C")

    for (item in list) {
        println(item)
    }

A
B
C

 

 

2、List的in

    val list = listOf("A", "B", "C")
    for (item: String in list) {
        println(item)
    }

A
B
C

 

 

3、list.indices

    val list = listOf("A", "B", "C")
    for (index in list.indices) {
        val str = "$index is ${list[index]}"
        println(str)
    }

0 is A
1 is B
2 is C

 

4、withIndex

    val list = listOf("A", "B", "C")

    // withIndex()
    for ((i, v) in list.withIndex()) {
        val str = "$i $v"
        println(str)
    }

0 A
1 B
2 C

 

5、m..n

    for (item in 1..5) {
        println(item)
    }

1
2
3
4
5

 

6、step

    for (item in 0..5 step 2) {
        println(item)
    }

0
2
4

 

 

7、downTo

    for (item in 5 downTo 1) {
        println(item)
    }

5
4
3
2
1

 

8、downTo - step

    for (item in 5 downTo 0 step 2) {
        println(item)
    }

5
3
1

 

 

9、util

    for (item in 0 until 5) {
        println(item)
    }

0
1
2
3
4

 

 

 

https://blog.csdn.net/zhangphil/category_12220817.htmlhttps://blog.csdn.net/zhangphil/category_12220817.html

 

你可能感兴趣的:(kotlin,kotlin)