1

It's easy to write simple loops like for (i in 0..10), but how to write more complex loops like:

for (byte i = 1 << 7; i != 0; i >>= 1)

or

for (byte i = 0x01; i != 0; i <<= 1)

Thanks for your help.

2 Answers 2

4

This is not what a for loop is for in Kotlin. You can use a normal while statement instead.

var i: Int = 1 shl 7
while (i != 0) {
    // . . .
    i = i shr 1
}
Sign up to request clarification or add additional context in comments.

Comments

2

In case you don't like having a var and are ok with using a Sequence, you could also use something like generateSequence instead, e.g.:

generateSequence(1 shl 7) {
  it shr 1
}
    .takeWhile { it != 0 }
    .forEach { ... }

// or: generateSequence(1 shl 7) { (it shr 1).takeIf { it != 0 } }.forEach { ... }

Otherwise Michaels answer about using while is perfectly fine.

2 Comments

I like avoiding vars and find myself using that style more and more (and sadly Java is quite bad at it). However, I guess for simple loops I will continue the old-fashioned way.
@MichaelPiefel I tend to use it nearly everywhere now... I really like that seed, next-value-function and loop-termination-condition are so near by each other... (maybe I also just saw for (seed; next-value-function; loop-termination-condition)-statements too often, so that I think I need this construct ;-)

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.