4

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.

1 Answer 1

7

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,") }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.