如何在Kotlin中编写for循环?Java计数式for循环的Kotlin等效代码是什么?
Kotlin For Loops: A Practical Guide (Including Java Equivalent)
Hey there! Let's break down how to work with for loops in Kotlin, including the direct equivalent of the Java loop you mentioned.
1. Common For Loop Patterns in Kotlin
Kotlin simplifies loop syntax compared to Java, with several flexible options:
- Range-based loops (most common for sequential counts)
Useuntilfor an exclusive upper bound (matchesi < Xlogic) or..for an inclusive range:// Exclusive range: runs i from 0 to 4 (stops before 5) for (i in 0 until 5) { // Your loop body here } // Inclusive range: runs i from 0 to 5 (includes 5) for (i in 0..5) { // Your loop body here } - Loops with step increments
If you need to skip values, addstepto your range:// Runs i = 0, 2, 4 for (i in 0 until 5 step 2) { // Your loop body here } - Iterating over collections
For lists, arrays, or other iterables, you can loop directly over elements without an index:val veggies = listOf("Carrot", "Spinach", "Broccoli") for (veggie in veggies) { println(veggie) }
2. Exact Equivalent of Your Java Loop
Your original Java code:
for(int i = 0; i < 5 ; i++) { // Loop body }
The Kotlin code that behaves exactly the same uses the until keyword, since it replicates the i < 5 condition perfectly:
for (i in 0 until 5) { // Your loop body goes here }
If you prefer to use an inclusive range instead, you could write 0..4 (since that's 5 iterations total), but 0 until 5 is more readable here because it directly mirrors the logic from your Java code.
内容的提问来源于stack exchange,提问作者Devrath
相关产品推荐
相关产品推荐

