为什么只有协程的main中的runBlocking无法编译? [英] Why does runBlocking in main with only a coroutine fail to compile?
本文介绍了为什么只有协程的main中的runBlocking无法编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用kotlinc-jvm 1.3.61
和kotlinx-coroutines-core-1.3.3
,以下代码无法编译.
Using kotlinc-jvm 1.3.61
and kotlinx-coroutines-core-1.3.3
, the following code fails to compile.
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
但是,以下代码将编译并成功运行.
however, the following code compiles and runs successfully.
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {}
print("") // The only addition
}
任何人都可以解释为什么仅添加print
语句就可以进行编译吗?
Can anyone explain why adding just a print
statement enables compilation?
推荐答案
main
函数不应返回任何内容(Unit
). runBlocking
返回其最后一个语句值,而launch
返回Job
,但是print
是Unit
函数.指定返回值类型可以解决此问题.
main
function should not return anything (Unit
). runBlocking
returns its last statement value and launch
returns Job
, but print
is a Unit
function. Specifying a return value type may solve this problem.
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
launch {}
}
这篇关于为什么只有协程的main中的runBlocking无法编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文