为什么只有协程的 main 中的 runBlocking 无法编译?
Why does runBlocking in main with only a coroutine fail to compile?
使用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
语句就能编译?
main
函数不应该 return 任何东西 (Unit
)。 runBlocking
return 是它的最后一个语句值,launch
return 是 Job
,但是 print
是一个 Unit
函数。指定 return 值类型可能会解决此问题。
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
launch {}
}
使用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
语句就能编译?
main
函数不应该 return 任何东西 (Unit
)。 runBlocking
return 是它的最后一个语句值,launch
return 是 Job
,但是 print
是一个 Unit
函数。指定 return 值类型可能会解决此问题。
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
launch {}
}