How can I do this java code in kotlin using just one for loop?
for(int i=0, j=0; i < 6 && j < 6; i++, j+=2) {
// code here
}
How can I do this java code in kotlin using just one for loop?
for(int i=0, j=0; i < 6 && j < 6; i++, j+=2) {
// code here
}
There is no way to iterate over multiple variables. In this case, the easiest thing you can do is:
for (i in 0..3) {
val j = i * 2
}
In a more general case, you can rewrite this as a while
loop:
var i = 0
var j = 0
while (i < 6 && j < 6) {
// code here
i++
j += 2
}
yole's answer is almost certainly the simplest and most efficient approach.
But one alternative you might look at is zipping sequences together, e.g.:
for ((i, j) in sequence{ yieldAll(0 until 6) }.zip(sequence{ yieldAll(0 until 6 step 2) })) {
// code here
}
That's much more readable with a utility function, e.g.:
fun <T, U> seqs(it1: Iterable<T>, it2: Iterable<U>)
= sequence{ yieldAll(it1) }.zip(sequence{ yieldAll(it2) })
for ((i, j) in seqs(0 until 6, 0 until 6 step 2)) {
// code here
}
That's less efficient (initially creating Iterables, Ranges, and Sequences, and then a Pair for each iteration). But it's the exact equivalent of the code in the question. And because it defines each range in one place, it does at least make them very clear.
(I think this needs Kotlin 1.3. There are probably simpler and/or more general ways of doing it; feel free to edit this if you can improve it!)