Search code examples
for-loopkotlinwhile-loopiteratorlanguage-design

How do you iterate a for loop with multiplication or division? [Kotlin]


How do you write an iteration step to multiply, divide, or have some custom iteration function in Kotlin? I know I can use while loops instead, but for loops seem more restrictive in scope than in other languages. Is this by design?

What is available in most other languages:

for(let i = 1; i <= 10; i *= 2) // [JavaScript]
for i := 1; i <= 10; i*=2 // [Golang]

What I want to do in Kotlin (or something close to it):

for(i in 1..10 step 2 * i) // [Kotlin]

It would be easy if we could reference the iterator in the for loop body itself, but the above will cause an 'Unresolved reference' error since i cannot be referenced in the iteration step.


Solution

  • Yes, it's a pity that Kotlin designers decided not to support C-style for loops, but you can do some tricks with extension functions.

    Declare infix function

    // for increasing rangeTo (..)
    infix fun IntRange.step(next: (Int) -> Int) =
            generateSequence(first, next).takeWhile { if (first < last) it <= last else it >= last }
    
    // for decreasing downTo
    infix fun IntProgression.step(next: (Int) -> Int) = (first..last).step(next)
    

    and use it like following

    for (i in 1..10 step { it * 2 }) {
        println(i)
    }
    

    Output

    1
    2
    4
    8
    

    And

    for (i in 16 downTo 1 step { it / 2 }) {
        println(i)
    }
    

    Output

    16
    8
    4
    2
    1