【问题标题】:Why does runBlocking in main with only a coroutine fail to compile?为什么只有协程的 main 中的 runBlocking 无法编译?
【发布时间】:2020-01-25 03:40:01
【问题描述】:

使用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 语句就可以编译?

【问题讨论】:

    标签: kotlin kotlin-coroutines


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-02-06
      • 2010-09-06
      • 1970-01-01
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多