如何从函数调用挂起函数

J_S*_*ton 4 suspend kotlin kotlin-coroutines

我试图在另一个挂起函数的参数中调用一个挂起函数。编译器实际上不允许这样做。它告诉我必须从挂起函数或协程调用挂起函数。

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

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

我怎样才能做到这一点?我需要isReady()在参数中。

Min*_*inn 7

您可以将挂起函数作为默认参数传递:

suspend fun compareElements(
    readyCheck: suspend () -> Boolean = { isReady() }
) {
    if (readyCheck()) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)