I have multi module kotlin gradle project in github here.
One of my sub project introducing-coroutines with build file build.gradle.kts file is here
The contents of build.gradle.kts is -
import org.jetbrains.kotlin.gradle.dsl.Coroutines
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
java
kotlin("jvm") version "1.3.11"
}
group = "chapter2"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
compile(kotlin("stdlib-jdk8"))
compile("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.0")
testCompile("junit", "junit", "4.12")
}
configure<JavaPluginConvention> {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
kotlin {
experimental {
coroutines = Coroutines.ENABLE
}
}
I'm trying to create my first coroutine program from this link.
import kotlinx.coroutines.*
import kotlinx.coroutines.async
import kotlin.system.*
import kotlin.system.measureTimeMillis
suspend fun computecr(array: IntArray, low: Int, high: Int): Long {
return if (high - low <= SEQUENTIAL_THRESHOLD) {
(low until high)
.map { array[it].toLong() }
.sum()
} else {
val mid = low + (high - low) / 2
val left = async { computecr(array, low, mid) }
val right = compute(array, mid, high)
return left.await() + right
}
}
When I compile the program I get the below error -
e: /Users/rajkumar.natarajan/Documents/Coding/coroutines-demo/introducing-coroutines/src/main/kotlin/SumUsingCoroutines.kt: (15, 20): Unresolved reference: async
> Task :introducing-coroutines:compileKotlin FAILED
FAILURE: Build failed with an exception.
I can import import kotlinx.coroutines.async
without any issue but not sure why I'm getting this error.
I have already verified similar issue here and added anko-commons
dependency here
How can I resolve this error?
First of all you have to remove from Gradle the part where you enable the experimental coroutine feature.
kotlin {
experimental {
coroutines = Coroutines.ENABLE
}
}
You cannot use async()
function implicitly anymore. You have to call it explicitly for a global scope coroutine GlobalScope.async(){...}
or you can call it from another coroutine scope using CoroutineScope(...).async{...}
or from scoping functions coroutineScope {...}
, withContext(...){...}
.
I have written an example for personal use to understand myself how coroutines are working. I hope it is good and helpful.