Unable to use coroutines in Kotlin (unresolved reference)

Viewed 1702

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

EDIT:

My build.gradle.kts file:

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

EDIT2: Everything fixed after clearing cache. You can do it in File->Invalidate caches

1 Answers

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!

EDIT:

If you still experience error messages of the form Unresolved reference: …,
you can try to fix the implementation in your gradle.build.kts from the one you posted in your question,

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

to this:

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

and try again. Hope that helps…

Related