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
相关产品推荐
相关产品推荐

