作者:zhouwenjun | 来源:互联网 | 2022-11-20 16:54
我在这里的 github中有多模块kotlin gradle项目。
我的子项目中的一个介绍协程的构建文件build.gradle.kts文件在这里
build.gradle.kts的内容是-
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 {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.withType {
kotlinOptions.jvmTarget = "1.8"
}
kotlin {
experimental {
coroutines = Coroutines.ENABLE
}
}
我正在尝试从此链接创建我的第一个协程程序。
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
}
}
当我编译程序时,出现以下错误-
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.
我可以导入import kotlinx.coroutines.async
而没有任何问题,但是不确定为什么会出现此错误。
我已经在这里验证了类似的问题,并在这里添加了anko-commons
依赖性
如何解决此错误?
1> LiTTle..:
首先,您必须从Gradle中删除启用实验协程功能的零件。
kotlin {
experimental {
coroutines = Coroutines.ENABLE
}
}
您不能再async()
隐式使用函数。您必须为全局范围协程显式GlobalScope.async(){...}
调用它,CoroutineScope(...).async{...}
或使用或从作用域函数coroutineScope {...}
,从其他协程范围调用它withContext(...){...}
。
我写了一个供个人使用的示例,以了解自己的协同程序是如何工作的。我希望它是有益和有益的。