Kotlin loop with irregular steps

I am trying to translate Java for an expression in Kotlin that produces this sequence:

1,2,4,8,16,32,64

This is the Java code:

for(int i = 1; i < 100; i = i + i) {
    System.out.printf("%d,", i);
}

The only way I found to transfer to Kotlin is:

var i = 1
while (i < 100) {
    print("$i,")
    i += i
}

I tried using step expressions, but this does not work. Is there a way to express this type of sequence more elegantly in Kotlin?

I know that you can use such code using Kotlin + Java 9:

Stream.iterate(1, { it <= 100 }) { it!! + it }.forEach { print("$it,") }

But it depends on the Java libraries, and I would prefer the native Kotlin libraries.

+4
source share
1 answer

generateSequence , takeWhile, , forEach for-in :

generateSequence(1) { it + it }.takeWhile { it < 100 }.forEach { print("$it,") }

+7

Source: https://habr.com/ru/post/1686273/


All Articles