Kotlin 中遍历List的N种方式

最近开发使用Kotlin确实挺爽的,就在于这门语言足够现代化,和JetBrains家的编辑器结合起来更是无敌了,自动提示,编译优化都是很实用的,但这样基本也脱离不了这个生态了,话说今天使用List的遍历,居然有六种方式,使用哪种方式都可以。这样虽然看起来很庞大,看起来很难记的样子,但是好在编译器+idea足够聪明,记住一两种就OK了。这有点像是我们学习英语,随着对语义的更加紧准的表达,英文单词拓展到了十几二十万个。(方便的同时也会加大人们的记忆负担)

方式0

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
brandList.forEach {
println(it)
}
brandList.forEach { println(it) }
    brandList.forEach {
        println(it)
    }

方式1

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for (brand in brandList) {
println(brand)
}
for (brand in brandList) { println(brand) }
    for (brand in brandList) {
        println(brand)
    }

方式2

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for (index in 0 until brandList.size) {
println("$index:${brandList[index]}")
}
for (index in 0 until brandList.size) { println("$index:${brandList[index]}") }
  for (index in 0 until brandList.size) {
        println("$index:${brandList[index]}")
    }

方式3

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for (index in 0..brandList.lastIndex) {
println("$index:${brandList[index]}")
}
for (index in 0..brandList.lastIndex) { println("$index:${brandList[index]}") }
    for (index in 0..brandList.lastIndex) {
        println("$index:${brandList[index]}")
    }

方式4

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for (index in brandList.indices) {
println("$index:${brandList[index]}")
}
for (index in brandList.indices) { println("$index:${brandList[index]}") }
    for (index in brandList.indices) {
        println("$index:${brandList[index]}")
    }

方式5

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
brandList.forEachIndexed { index, brand ->
println("$index:${brand}")
}
brandList.forEachIndexed { index, brand -> println("$index:${brand}") }
    brandList.forEachIndexed { index, brand ->
        println("$index:${brand}")
    }

Leave a Reply

Your email address will not be published. Required fields are marked *