gpt4 book ai didi

kotlin - Kotlin是否按顺序等待参数?

转载 作者:行者123 更新时间:2023-12-02 13:12:06 25 4
gpt4 key购买 nike

Kotlin是否严格按照顺序等候

  • receiver.await()
  • msg.await()

  • 在第7行:
     suspend fun sendEmail(r: String, msg: String): Boolean { //(6)
    delay(2000)
    println("Sent '$msg' to $r")
    return true
    }

    suspend fun getReceiverAddressFromDatabase(): String { //(4)
    delay(1000)
    return "coroutine@kotlin.org"
    }

    suspend fun sendEmailSuspending(): Boolean {
    val msg = async(CommonPool) { //(3)
    delay(500)
    "The message content"
    }
    val recipient = async(CommonPool) { //(5)
    getReceiverAddressFromDatabase()
    }
    println("Waiting for email data")
    val sendStatus = async(CommonPool) {
    sendEmail(recipient.await(), msg.await()) //(7)
    }
    return sendStatus.await() //(8)
    }

    或以任何顺序?我的意思是说Kotlin会先检查是否有receive.await(),然后才完成对msg.await()的检查?

    最佳答案

    您的问题不是await特定的,而是更深入地探讨了Kotlin本身的评估顺序语义。

    因此,这是Kotlin language specification的报价:

    Function arguments are then evaluated in the order of their appearance in the function call left-to-right



    应用于您的代码行:
    sendEmail(recipient.await(), msg.await())

    很显然,首先评估 recipient.await(),然后评估 msg.await()。直到相关的 await()完成后, Deferred调用才会完成。

    关于kotlin - Kotlin是否按顺序等待参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59752395/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com