为什么只有协程的main中的runBlocking无法编译? [英] Why does runBlocking in main with only a coroutine fail to compile?

查看:82
本文介绍了为什么只有协程的main中的runBlocking无法编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用kotlinc-jvm 1.3.61kotlinx-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,但是printUnit函数.指定返回值类型可以解决此问题.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆