我有以下代码。
我无法理解为什么会发生这种情况。我发现没有关于此问题的现有答案。我尝试将await直接放在tenny和twy被分配的地方,但这也不起作用。
我认为依赖项没有问题,因为 aysnc 可以工作。我还发布了我的 build.gradle 文件。
import kotlinx.coroutines.experimental.async
fun main(args: Array<String>) {
async{
val tenny = star_ten(1)
val twy =star_two(10)
println()
println(twy.await()+tenny.await())
println()
}
}
fun star_two(num:Int):Int{
return num * 2
}
fun star_ten(num:Int):Int{
return num * 10
}
我的build.gradle是
group 'org.nul.cool'
version '1.0-SNAPSHOT'
buildscript {
ext.kotlin_version = '1.1.60'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'java'
apply plugin: 'kotlin'
kotlin {
experimental {
coroutines 'enable'
}
}
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
testCompile group: 'junit', name: 'junit', version: '4.12'
compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.19.2"
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
最佳答案
您收到 await()
的未解析引用,因为您的 star_two
和 star_ten
函数返回 Int
,所以 tenny
和 twy
变量只是 Int
。 await()
函数在 Deferred
上声明。简而言之,您没有在这些函数中执行任何异步操作,因此无需等待。
使这些函数异步运行的一种方法是将它们声明为挂起函数并在异步 block 中调用它们。像这样的东西(未经测试)...
async{
val tenny = async { star_ten(1) } //Should be Deferred<Int>
val twy = async { star_two(10)} //Should be Deferred<Int>
println(twy.await() + tenny.await())
}
suspend fun star_two(num:Int): Int = num * 2
suspend fun star_ten(num:Int): Int = num * 10
Guide to kotlinx.coroutines by example页面有很多很好的例子,特别是 this section .
关于java - 异步工作,但等待 Unresolved reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47342375/