PAYATHON 2026

如何理解文档中的 CoroutineScope.() 函数签名?

数据小陈

结论

CoroutineScope.() -> Unit 是带接收者的函数类型(function type with receiver)。在 block: suspend CoroutineScope.() -> Unit 中,block 是一个可挂起函数:没有普通参数,返回 Unit,接收者类型为 CoroutineScope。所以传入的 lambda 内部可以直接通过 this 访问 CoroutineScope 的成员。这里的 this 指这个协程作用域,不会指向外层类。

如何阅读这个签名

拆开来看:

public fun LaunchedEffect(
    key1: Any?,
    block: suspend CoroutineScope.() -> Unit
): Unit
  • key1: Any?:控制 effect 是否重启的 key。
  • block:要执行的 lambda。
  • suspend:这个 lambda 是挂起函数,内部可以调用 delay、withContext 等挂起 API。
  • CoroutineScope.:接收者类型。lambda 体会在某个 CoroutineScope 上运行,可以直接调用该作用域的成员。
  • () -> Unit:没有参数,返回 Unit。

block 更接近“扩展函数类型”:调用方传入的 lambda 会在 CoroutineScope 接收者上执行。普通的 () -> Unit 没有接收者,而 (CoroutineScope) -> Unit 会把作用域当作普通参数传入。概念上可以把接收者看成第一个参数,但源码中这个接收者通过 this 使用,it 并不指向它。

代码示例

在 LaunchedEffect 中,lambda 内可以直接调用 launch:

LaunchedEffect(Unit) {
    // this 是 CoroutineScope
    launch {
        delay(1000)
        // 执行异步工作
    }
}

也可以显式写出接收者:

LaunchedEffect(key1 = Unit) {
    this.launch {
        // ...
    }
}

单独声明这种函数类型时,可以这样写:

val block: suspend CoroutineScope.() -> Unit = {
    launch {
        // 这里可直接访问 CoroutineScope 的成员
    }
}

如果自己写一个接收这类 lambda 的函数,可以这样调用:

suspend fun runInScope(
    scope: CoroutineScope,
    block: suspend CoroutineScope.() -> Unit
) {
    scope.block()
}

scope.block() 中的 scope 就是 block 的接收者。

注意事项

  • CoroutineScope.() -> Unit 本身是类型,不是对象。使用时需要传入具体的 lambda 或函数引用。
  • suspend 修饰整个函数类型,表示调用 block 时可能挂起。
  • 不要把它和扩展函数声明混淆。这里是函数类型中的接收者,并非定义 fun CoroutineScope.xxx()。
  • 在 Compose 中,LaunchedEffect 的 key1 变化会导致 effect 取消并重启;block 会在对应的协程作用域中执行。具体行为以所用 Compose 版本文档为准。

备注:内容仅供参考。