1

I'm learning Coroutines of Kotlin, I'm a beginner of running code online in https://try.kotlinlang.org/

I try to test Code A in the website, but I get many errors just like Image A, how can I fix it?

Code 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()

}

Image A enter image description here

HelloCW
  • 843
  • 22
  • 125
  • 310

1 Answers1

2

Try to run following code:

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()

}

Output would be :)

Cancelling child
Child is cancelled
Parent is not cancelled
Shreeya Chhatrala
  • 1,441
  • 18
  • 33
  • The reason this works is that `launch` is (now) an extension method of `CoroutineScope`, so you have to have a `CoroutineScope` as the (implicit or explicit) receiver of `launch`, that is, the `this` in `this.launch`. That `CoroutineScope` is provided as implicit `this` by the `runBlocking` call. Without it, you're trying to call `CoroutineScope.launch()` as if `launch` were in the global namespace, but it's not. Apparently this has changed: See https://stackoverflow.com/a/54285142/423105 where it says "anymore". – LarsH May 19 '20 at 23:39