For example:
for ((x, y) in (1..100, 50 downTo 0)) {} for ((x, y, z) in (1..100, 50 downTo 0, 500..1000 step 2)) {} I have found the official kotlin document: Destructuring Declarations, but still can't write correct code.
For example:
for ((x, y) in (1..100, 50 downTo 0)) {} for ((x, y, z) in (1..100, 50 downTo 0, 500..1000 step 2)) {} I have found the official kotlin document: Destructuring Declarations, but still can't write correct code.
You can create a zipOf function, which returns a Sequence of all possible combinations. Here are 3 overloads of this function:
fun <T1, T2> zipOf(first: Iterable<T1>, second: Iterable<T2>) = sequence { for (t1 in first) for (t2 in second) yield(t1 to t2) } fun <T1, T2, T3> zipOf(first: Iterable<T1>, second: Iterable<T2>, third: Iterable<T3>) = sequence { for (t1 in first) for (t2 in second) for (t3 in third) yield(Triple(t1, t2, t3)) } fun <T> zipOf(vararg iterables: Iterable<T>): Sequence<List<T>> = iterables.fold(sequenceOf(emptyList())) { result, iterable -> result.flatMap { list -> iterable.asSequence().map { elm -> list + elm } } } You can use them like this:
for ((x, y) in zipOf(1..100, 50 downTo 0)) {} for ((x, y, z) in zipOf(1..100, 50 downTo 0, 500..1000 step 2)) {} for ((x, y, z, w) in zipOf(1..100, 50 downTo 0, 500..1000 step 2, 0..1)) {}
{(x,y) | x in [1, 100] and y in [0, 50]}? (<- that's math notation, not python syntax)zipis what you are looking for, e.g.:(1..100).zip(50 downTo 0).forEach { (x, y) -> /* do something */ }...(1..100).zip(50 downTo 0).zip(500..1000 step 2).forEach { (xy, z) -> xy.also { (x, y) -> /* do something with x, y and z */ } }... Note that if any of those ranges finishes earlier, it will stop with the latest possible value... e.g. in the last example the highestzwould be600...for (x in 1..100) { for (y in 50 downTo 0) { for (z in 500..1000 step 2) { /* do something with x, y and z */ }}}