获取以下两个代码示例(分别取自 Kotlin 文档和协程库 README):
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(2000)
println("World")
}
println("Hello")
}
Run Code Online (Sandbox Code Playgroud)
在 Kotlin >= 1.3.0 中,可以将main()函数标记为suspend能够并直接使用 a coroutineScope。
import kotlinx.coroutines.*
suspend fun main() = coroutineScope {
launch {
delay(2000)
println("World")
}
println("Hello")
}
Run Code Online (Sandbox Code Playgroud)
两者产生相同的输出:
Hello
World
Run Code Online (Sandbox Code Playgroud)
这两种方法之间有功能差异吗?如果有,它们是什么?