Say I have `fun myCheck(): Boolean` which I want t...
# getting-started
m
Say I have
fun myCheck(): Boolean
which I want to repeatedly call until it returns false. If I use
while (myCheck()) {}
then I get a warning saying “control flow with empty body”. So I guess
while
is supposed to be used with a non-empty body. Does this mean there is a more appropriate way?
f
Yep, It seems you want to run some code while your condition is true, so put your code inside the
while
m
But there is no code to run while the condition is true. The check does all that is needed.
f
So you can try this:
Copy code
do {
        val bool = myCheck()
    }while(bool)
e
Write a comment inside that it is intentionally empty.
👍 7
m
Copy code
var index = start
while (myCheck(index++)) { /* nothing to do */ }
Very much a style question, but I just wonder if there is a neater way - probably a for loop so that
index
is encapsulated, but then the code is maybe too verbose.
a
Copy code
var index = start
while (myCheck(index++)) { continue; }
m
The equivalent of in Java;
Copy code
for (int index = start; myCheck(index); index++) { /*do nothing */ }
k
There’s also
Copy code
generateSequence(start){ it+1 }.takeWhile(::myCheck).count()
if you want to be kooky. :)
j
Spinning on a check like this is not very good for battery life or energy consumption. The check could be executed millions of times a second. Have you considered some other synchronisation method. E.g. condition variable, countdown latch....