kotlin - 如何从函数调用挂起函数

标签 kotlin kotlin-coroutines suspend

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

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

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

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

最佳答案

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

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

关于kotlin - 如何从函数调用挂起函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59441979/

相关文章:

node.js - 使用 "it"覆盖 mocha "yield"以支持 "suspend"

kotlin - 如何强制 Kotlin "when"涵盖所有可能的选项?

android - 输出顺序显示错误

android - 使用 withContext 方法在 kotlin 协程中进行 try-catch

kotlin - Kotlin是否按顺序等待参数?

kotlin - Kotlin:在列表 “in parallel”上应用暂停功能?

android - Kotlin 和惯用的编写方式, 'if not null, else...' 基于可变值

kotlin - 获取非包扩展属性的属性

kotlin - 等待循环中的所有流程完成

Windows SuspendThread 没有? (GetThreadContext 失败)