Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a traditional for-loop in Kotlin

JavaScript

for (var x = 0; x < 360; x += 0.5)
{
  // ...
}

How do I do this in Kotlin?


Note that my step size is a floating point and so a regular range won't work:

for (x in 0.0 until 360.0 step 0.5) {
  // ...
}

I also need to exclude the ending value, hence why I'm using until.


I will resort to a while loop for now:

var x = 0.0;

while (x < 360.0) {
  // ...
  x += 0.5
}
like image 361
David Callanan Avatar asked Oct 24 '25 11:10

David Callanan


1 Answers

There isn't a way to do this right now in Kotlin because Kotlin does not have "traditional" for loops. I believe you're right in choosing a while loop. In fact, traditional for loops are just while loops in disguise:

for (init; condition; post) {
    // do something
}

can always be rewritten,

init
while (condition) {
    // do something
    post
}

with no change in behavior, because the init statement will always execute and the condition will always be checked before the loop runs even once. One thing this construct can't give you is a variable that's only scoped to this block. If you're really after that behavior, the following would work, though it's not very idiomatic.

for (x in generateSequence(0.0) { it + 0.5 }.takeWhile { it < 360.0}) {
    println(x)
}

If you're using a Sequence, you might also be interested in the more idiomatic forEach:

generateSequence(0.0) { it + 0.5 }.takeWhile { it < 360.0 }.forEach { x ->
    // do something
}
like image 136
Adam Avatar answered Oct 27 '25 00:10

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!