【问题标题】:Unable to use coroutines in Kotlin (unresolved reference)无法在 Kotlin 中使用协程(未解决的参考)
【发布时间】:2021-12-16 06:14:54
【问题描述】:

我创建了 gradle java kotlin 项目。我想使用协程,但我收到 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")
}

在 build.gradle.kts 中,我将这一行包含在依赖项块中:

implementation("org.jetbrains.kotlinx", "kotlinx-coroutines-core", "1.5.2")

编辑:

我的 build.gradle.kts 文件:

plugins {
    kotlin("jvm") version "1.5.10"
    java
}

group = "org.example"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    implementation(kotlin("stdlib"))
    testImplementation("org.junit.jupiter:junit-jupiter-api:5.6.0")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2")
}

tasks.getByName<Test>("test") {
    useJUnitPlatform()
}

编辑2: 清除缓存后一切都修复了。您可以在 File->Invalidate caches 中执行此操作

【问题讨论】:

    标签: java kotlin gradle kotlin-coroutines coroutine


    【解决方案1】:

    你必须在这里使用runBlocking,否则不会有一个Coroutine Scope你可以调用launchdelay

    工作示例与您的非常相似(取自 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
    }
    

    输出(如预期):

    Hello
    World!
    

    编辑:

    如果您仍然遇到 Unresolved reference: … 形式的错误消息,
    您可以尝试修复您在问题中发布的gradle.build.kts 中的implementation

    implementation("org.jetbrains.kotlinx", "kotlinx-coroutines-core", "1.5.2")
    

    到这里:

    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2")
    

    然后再试一次。希望对您有所帮助……

    【讨论】:

    • 是一样的。未解决的参考 runBlocking @deHaar
    • @vytaute 看我的编辑,我不认为 Kotlin 代码有错,所以我猜是协程的 gradle 导入。
    • 对此非常抱歉...它必须与库导入有关(关键字在您的代码中不可用),也许尝试使用 maven 设置相同的项目,甚至尝试清理项目和 ide 缓存。
    • 清除缓存确实有帮助!非常感谢!
    • 酷,很高兴它有帮助!
    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    相关资源
    最近更新 更多