I created gradle java kotlin project. I want to use coroutines but I get unresolved reference launch
and unresolved reference delay
errors:
import java.util.*
import kotlinx.coroutines.*
fun main (args: Array<String>)
{
launch { // launch coroutine
delay(1000L)
println("World!")
}
println("Hello")
}
In build.gradle.kts I included this line in dependencies block:
implementation("org.jetbrains.kotlinx", "kotlinx-coroutines-core", "1.5.2")
You have to use runBlocking
here, otherwise there won't be a Coroutine Scope where you could call launch
and delay
.
Working example very similar to yours (taken from your first coroutine ):
fun main(args: Array<String>) = runBlocking { // this: CoroutineScope
launch { // launch a new coroutine and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello") // main coroutine continues while a previous one is delayed
}
Output (as expected):
Hello
World!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.