Home > database >  While with empty body
While with empty body

Time:12-20

I have a line of code calling a method that return a boolean. I want to call this method until it return falss. To do so I have a while loop but I do not need a body as all is done isnide the method called as condition.

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

    }

Is there a prettier way to do that ? I was thinking to something like repeateUntil(method,condtion)

Thx

CodePudding user response:

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
}

CodePudding user response:

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

CodePudding user response:

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

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