使用kotlinc-jvm 1.3.61
和kotlinx-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
语句就能启用编译功能?
答案 0 :(得分:3)
main
函数不应返回任何内容(Unit
)。 runBlocking
返回其最后一个语句值,而launch
返回Job
,但是print
是Unit
函数。指定返回值类型可以解决此问题。
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
launch {}
}