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

Kotlin/Native暂不支持suspend fun main(),求等效实现方案?

Kotlin/Native中suspend fun main()的等效实现

在Kotlin/JVM中可以直接使用suspend fun main()作为协程入口,但Kotlin/Native目前暂不支持挂起函数作为程序入口,会抛出编译错误:

e: Entry point can not be a suspend function.

在该特性落地前,针对Kotlin/Native v1.7.22和Kotlinx Coroutines 1.6.4版本,可通过**普通main函数结合runBlocking**实现等效逻辑:

import kotlinx.coroutines.*

fun main() = runBlocking {
    doWorld()
}

suspend fun doWorld() = coroutineScope {
    launch {
        delay(1000L)
        println("World!")
    }
    println("Hello")
}

原理说明

runBlocking会创建一个阻塞当前主线程的协程作用域,直到作用域内所有协程任务执行完毕才会退出,完美模拟了suspend fun main()的行为:既可以在内部调用挂起函数,又能保证程序等待所有协程任务完成后再终止。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:20:27