kotlinkotlin-coroutinessuspend

How to Call Suspend Function from Function


I am trying to call a suspend function in the parameters of another suspend function. The compiler doesn't actually allow this. It is telling me that a suspend function must be called from a suspend function or coroutine.

suspend fun compareElements(
    isReady: Boolean = isReady() // IDE complains.
) {
   ...
}

//This is for this questions purpose. Reality is a bit more complex.
suspend fun isReady() = true

How can I do this? I need to have isReady() in the parameter.


Solution

  • You can pass a suspend function instead as a default parameter:

    suspend fun compareElements(
        readyCheck: suspend () -> Boolean = { isReady() }
    ) {
        if (readyCheck()) {
            ...
        }
    }