Search code examples
javaintellij-ideakotlinopen-source

Async working, but getting unresolved reference for await


I have the following code.

I am unable to understand why this is happening. I found no existing answer on SO covering this. I tried putting await directly where tenny and twy are assigned, but that too doesn't work.

I don't think there is a problem with the dependencies because aysnc works. I have also posted my build.gradle file.

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
}

My build.gradle is

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"
}

Solution

  • You are getting an unresolved reference for await() because your star_two and star_ten functions return Int, so tenny and twy variables are just Int. The await() function is declared on a Deferred. In short, you aren't doing anything asynchronous in those functions so there's nothing to await.

    One way to get those functions to behave asynchronously is to declare them as suspending functions and call them each in an async block. Something like this (untested)...

    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
    

    The Guide to kotlinx.coroutines by example page has many good examples, especially this section.