Kotlin 为什么我会得到这个错误;未解析的引用:launch“;我什么时候测试代码?
我正在学习Kotlin的协同程序,我是一个在线运行代码的初学者 我试着在网站上测试代码A,但是我得到了很多错误,就像图片A一样,我如何修复它 代码AKotlin 为什么我会得到这个错误;未解析的引用:launch“;我什么时候测试代码?,kotlin,kotlin-coroutines,Kotlin,Kotlin Coroutines,我正在学习Kotlin的协同程序,我是一个在线运行代码的初学者 我试着在网站上测试代码A,但是我得到了很多错误,就像图片A一样,我如何修复它 代码A import kotlinx.coroutines.* fun main(args: Array<String>) { val job = launch { val child = launch { try { delay(Long.MAX_VALUE)
import kotlinx.coroutines.*
fun main(args: Array<String>) {
val job = launch {
val child = launch {
try {
delay(Long.MAX_VALUE)
} finally {
println("Child is cancelled")
}
}
yield()
println("Cancelling child")
child.cancel()
child.join()
yield()
println("Parent is not cancelled")
}
job.join()
}
导入kotlinx.coroutines*
趣味主线(args:Array){
val作业=启动{
val child=launch{
试一试{
延迟(长最大值)
}最后{
println(“取消子项”)
}
}
收益率()
println(“取消子项”)
child.cancel()
child.join()
收益率()
println(“未取消父项”)
}
job.join()
}
图像A
尝试运行以下代码:
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
fun main() = runBlocking<Unit> { //here i made change
val job = launch {
val child = launch {
try {
delay(Long.MAX_VALUE)
} finally {
println("Child is cancelled")
}
}
yield()
println("Cancelling child")
child.cancel()
child.join()
yield()
println("Parent is not cancelled")
}
job.join()
}
之所以这样做,是因为
launch
现在是CoroutineScope
的一种扩展方法,所以你必须有一个CoroutineScope
作为launch
的(隐式或显式)接收者,也就是this.launch
中的this
。runBlocking
调用将CoroutineScope
作为隐式this
提供。如果没有它,您将试图调用CoroutineScope.launch()
,就像launch
在全局命名空间中一样,但它不是。显然这已经改变了:看看它在哪里说“不再”。
Cancelling child
Child is cancelled
Parent is not cancelled