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.
source
share