为什么只有协程的main中的runBlocking无法编译?

时间:2020-01-25 03:40:01

标签: kotlin kotlin-coroutines

使用kotlinc-jvm 1.3.61kotlinx-coroutines-core-1.3.3,以下代码无法编译。

import kotlinx.coroutines.*
fun main() = runBlocking {
    launch {}
}

有错误

Error: Main method not found in class SomeExampleKt, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

但是,以下代码将编译并成功运行。

import kotlinx.coroutines.*
fun main() = runBlocking {
    launch {}
    print("") // The only addition
}

谁能解释为什么仅添加print语句就能启用编译功能?

1 个答案:

答案 0 :(得分:3)

main函数不应返回任何内容(Unit)。 runBlocking返回其最后一个语句值,而launch返回Job,但是printUnit函数。指定返回值类型可以解决此问题。

import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
    launch {}
}
相关问题