Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 877
J_Strauton Avatar asked Jan 26 '23 11:01

J_Strauton


1 Answers

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

suspend fun compareElements(
    readyCheck: suspend () -> Boolean = { isReady() }
) {
    if (readyCheck()) {
        ...
    }
}
like image 52
Minn Avatar answered Mar 08 '23 08:03

Minn