简体   繁体   English

无法在 Kotlin 中使用协程(未解析的参考)

[英]Unable to use coroutines in Kotlin (unresolved reference)

I created gradle java kotlin project.我创建了 gradle java kotlin 项目。 I want to use coroutines but I get unresolved reference launch and unresolved reference delay errors:我想使用协程,但出现unresolved reference launchunresolved reference delay错误:

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:在 build.gradle.kts 中,我在依赖项块中包含了这一行:

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 .你必须在这里使用runBlocking ,否则不会有一个Coroutine Scope可以调用launchdelay

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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM