Reputation: 181
I have a line of code calling a method that returns a boolean.
I want to call this method until it returns false
. To do so I have a while loop, but it does not need a body as everything is done inside the method called as the condition.
while (grid.sandGoesDow(500, 0)) {
}
Is there a prettier way to do this?
I was thinking to something like repeatUntil(method, condition)
.
Upvotes: 0
Views: 908
Reputation: 199215
You can create a repeatWhileTrue
method:
void whileTrue(Supplier<Boolean> action) {
while(action.supply());
}
Usage
whileTrue(()->grid.sandGoesDow(500, 0));
Beauty is in the eye of the beholder, so that might not be prettier.
Edit:
fun whileTrue(action: () -> Boolean) {
while(action.invoke());
}
Usage:
whileTrue { grid.sandGoesDow(500, 0) }
See a running example: https://pl.kotl.in/4_b_huSfX
Upvotes: 1
Reputation: 265151
Not really. You could use a semicolon, but that's obscure. You should avoid it.
while (grid.sandGoesDow(500, 0))
;
The most maintainable option is to put a code comment into your loop's body:
while (grid.sandGoesDow(500, 0)) {
/* busy wait for condition */
}
while (grid.sandGoesDow(500, 0)) {
// do nothing
}
Upvotes: 2
Reputation: 3226
In Kotlin you can describe a void action with Unit
object.
while (grid.sandGoesDow(500, 0)) { Unit }
Upvotes: 1