Quentin M
Quentin M

Reputation: 181

While with empty body

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

Answers (3)

OscarRyz
OscarRyz

Reputation: 199215

You can create a repeatWhileTrue method:

Java

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:

Kotlin

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

knittl
knittl

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

Steyrix
Steyrix

Reputation: 3226

In Kotlin you can describe a void action with Unit object.

while (grid.sandGoesDow(500, 0)) { Unit }

Upvotes: 1

Related Questions