如何在Kotlin中实现无内层循环的双索引for循环?
Great question! Kotlin gives you a few clean ways to replicate that dual-index, start-and-end traversal you use in Java—no inner loops required. Let’s walk through the options:
1. Direct 1:1 Translation of Your Java Loop
If you want something that feels almost identical to your Java code, Kotlin supports a traditional-style for loop with multiple variables. You just need to adjust the syntax slightly:
val myArray = arrayOf(1, 2, 3, 4, 5) var j = 0 var k = myArray.lastIndex // Equivalent to myArray.length - 1 in Java for (; j < myArray.size; j++, k--) { // Access elements using both indices println("Element at start: ${myArray[j]}, Element at end: ${myArray[k]}") }
This works exactly like your Java version: j increments from the start, k decrements from the end, and the loop runs until j covers the entire array length.
2. Idiomatic Kotlin with Indices and Zip
For a more concise, Kotlin-native approach, you can pair the array’s indices with its reversed indices using zip(). This lets you iterate over pairs of start/end indices directly:
val myArray = arrayOf(1, 2, 3, 4, 5) for ((startIndex, endIndex) in myArray.indices.zip(myArray.indices.reversed())) { println("Start: ${myArray[startIndex]}, End: ${myArray[endIndex]}") }
If you don’t even need the indices (just the elements themselves), you can simplify further by zipping the array with its reversed copy:
val myArray = arrayOf(1, 2, 3, 4, 5) for ((startElement, endElement) in myArray.zip(myArray.reversed())) { println("Start element: $startElement, End element: $endElement") }
This is cleaner when your logic only cares about the elements, not their positions in the array.
3. While Loop for Fine-Grained Control
If you prefer even more control over the loop conditions (like stopping when j passes k to avoid redundant iterations), a while loop works perfectly:
val myArray = arrayOf(1, 2, 3, 4, 5) var j = 0 var k = myArray.lastIndex while (j <= k) { println("j: ${myArray[j]}, k: ${myArray[k]}") j++ k-- }
This is useful if you want to stop traversing once the two indices meet or cross, instead of going through the entire array length.
All these approaches avoid inner loops and let you traverse from both ends of the array simultaneously—pick the one that fits your code style and use case best!
内容的提问来源于stack exchange,提问作者Suraju Ogundele

