java - 异步工作,但等待 Unresolved reference

标签 java intellij-idea kotlin open-source

我有以下代码。

我无法理解为什么会发生这种情况。我发现没有关于此问题的现有答案。我尝试将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_twostar_ten 函数返回 Int,所以 tennytwy 变量只是 Intawait() 函数在 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/

相关文章:

java - 如何使用 Struts 2 将图像文件插入 MySql 数据库

java - java中从Exception类抛出异常

java - Maven 通过直接 http ://link 安装 .jar 文件

java - 如果基类匹配条件,IntelliJ 结构搜索将查找派生类

android - 膨胀类 androidx.fragment.app.FragmentContainerView 时出错

android - 无法访问 Activity 绑定(bind) android

android - Autocompletetextview返回参数指定为非null为null

java - 找不到 IndexSearcher.search 的来源(查询查询,过滤器过滤器,int n)

intellij-idea - intellij idea构建项目时找不到java

java - Gradle 同步失败 : Unable to find method org. gradle.api.artifacts.ProjectDependency.getProjectConfiguration()Lorg/gradle/api/artifacts/Configuration