Coroutine sample code fail to compile on unresolved reference kotlinx


#1

New to Kotlin here. I was trying to follow the coroutines sample code https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html but wasn’t able to get the code to even compile. It failed on unresolved reference: kotlinx

I have updated the gradle script accordingly as well. What am I missing? Thanks.

Using Intellij CE 2017.2, and Kotlin is v1.1.51

buildscript {
    ext.kotlin_version = '1.1.51'

    repositories {
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_version"
    }
}

apply plugin: 'kotlin'

kotlin {
    experimental {
        coroutines 'enable'
    }
}

repositories {
    jcenter()
}

sourceSets {
    main.kotlin.srcDirs += 'src/main/kotlin'
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_version"
}

import kotlin.coroutines.experimental.*

fun main(args: Array<String>) {
    println("Start")

    // Start a coroutine
    launch(CommonPool) {
        delay(1000)
        println("Hello")
    }

    Thread.sleep(2000) // wait for 2 seconds
    println("Stop")
}


#2

kotlinx-coroutines-core is a separate library which has its own versioning, so you shouldn’t specify the kotlin_version as its version. The latest version of this library currently is 0.19.

Also there’s no need to specify this library as a classpath dependency of gradle build script, because this library is a dependency for compiling your code and not for running the build script.


#3

Thank you Ilya. After I fixed the gradle file, I still ran into the same issue. After some more investigation, I realized everything was running using Java 9. It worked with the fixed gradle file when I changed the JDK to 1.8.