Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 为什么我会得到这个错误;未解析的引用:launch“;我什么时候测试代码?_Kotlin_Kotlin Coroutines - Fatal编程技术网

Kotlin 为什么我会得到这个错误;未解析的引用:launch“;我什么时候测试代码?

Kotlin 为什么我会得到这个错误;未解析的引用: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)        

我正在学习Kotlin的协同程序,我是一个在线运行代码的初学者

我试着在网站上测试代码A,但是我得到了很多错误,就像图片A一样,我如何修复它

代码A

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