HelloCW
HelloCW

Reputation: 2335

Why do I get the error "Unresolved reference: launch" when I test the code?

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

Upvotes: 1

Views: 1242

Answers (1)

Shreeya Chhatrala
Shreeya Chhatrala

Reputation: 1449

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

Upvotes: 2

Related Questions