提问者:小点点

对静态编程语言协程感到困惑


这没有编译错误:

suspend fun test() {
    runBlocking {

    }
}

这有一个编译错误:

suspend fun test() {
    launch {

    }
}

未解决的参考。由于接收者类型不匹配,以下候选项均不适用:公共乐趣CoroutineScope.启动(上下文:CoroutineContext=…,start:CoroutineStart=…,block:挂起CoroutineScope。()-

我真的不明白问题是什么…


共1个答案

匿名用户

协程在某些CoroutineScope的上下文中使用启动协程生成器启动:

fun test() = CoroutineScope(Dispatchers.Main).launch {
}

启动-是CoroutineScope对象上的扩展函数,定义如下:

public fun CoroutineScope.launch(...): Job {}

runBlock-不是扩展函数,所以可以作为常规函数调用,定义如下:

public fun <T> runBlocking(...): T {}