javaloopskotlin

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).


Solution

  • 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