You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中实现带类型推断的Promise.all等效方案,解决类型推断失效问题

Kotlin并行协程调用的类型推断问题解决办法

在TypeScript中,我们可以通过Promise.all并行执行异步函数,且类型推断会自动生效:

const [myNumber, myString] = await Promise.all([firstFunction(), secondFunction()])

TypeScript能智能识别firstFunction返回number类型、secondFunction返回string类型,自动为变量分配对应类型。

你找到的Kotlin写法存在类型推断失效的问题:

val (myNumber, myString) = coroutineScope {
    arrayOf(async {
        firstFunction()
    }, async {
        secondFunction()
    }).map { it.await() }
}

这段代码中,arrayOf会将两个不同返回类型的Deferred实例统一推断为Deferred<out Any>,调用map后得到的是List<Any>,解构时两个变量自然都会被推断为Any类型。

可行的解决办法

直接分别定义Deferred变量,再通过Pair组合结果,Kotlin就能正确推断类型:

val (myNumber, myString) = coroutineScope {
    val numDeferred = async { firstFunction() }
    val strDeferred = async { secondFunction() }
    numDeferred.await() to strDeferred.await()
}

这里numDeferred.await()会返回firstFunction的实际类型,strDeferred.await()返回secondFunction的实际类型,to操作符生成的Pair会被推断为Pair<NumberType, StringType>,解构时myNumber和myString就能获得正确的类型。

如果需要处理更多返回值,可以自定义data class替代Pair,原理相同:

data class Result(val num: Int, val str: String)

val (myNumber, myString) = coroutineScope {
    val numDeferred = async { firstFunction() }
    val strDeferred = async { secondFunction() }
    Result(numDeferred.await(), strDeferred.await())
}

内容的提问来源于stack exchange,提问作者Gabriel Furstenheim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 20:48:29