I have been trying to translate a Java for expression into Kotlin which 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 have found to translate this into Kotlin is:
var i = 1
while (i < 100) {
print("$i,")
i += i
}
I have tried to use step expressions, but this does not seem to work. Is there any way to express this type of sequence more elegantly in Kotlin?
I know you can have code like this one using Kotlin + Java 9:
Stream.iterate(1, { it <= 100 }) { it!! + it }.forEach { print("$it,") }
But this relies on Java libraries and I would prefer Kotlin native libraries.
You can use the generateSequence
function to create an infinite sequence, then use takeWhile
to limit it at a specific value and then use forEach
instead of a for-in
construct to handle each iteration:
generateSequence(1) { it + it }.takeWhile { it < 100 }.forEach { print("$it,") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With