Ryan Pierce
Ryan Pierce

Reputation: 1633

Why does runBlocking in main with only a coroutine fail to compile?

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 {}
}

with error

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
}

Can anyone explain why adding just a print statement enables compilation?

Upvotes: 1

Views: 858

Answers (1)

IR42
IR42

Reputation: 9672

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 {}
}

Upvotes: 10

Related Questions