Hi ! I'm trying to run several launch in a runBloc...
# coroutines
l
Hi ! I'm trying to run several launch in a runBlocking call, but the program fails running, throw an exception : why ? Here's my playground : https://pl.kotl.in/CgNQGBdiE
βœ… 1
s
The
runBlocking
function is using the last line of its code block as its return value, which in this case is a
Job
. The
main()
function needs to return
Unit
!
πŸ‘ 1
j
This is an unfortunate side-effect of the inferred return type for your main function. Because you declared
fun main() = runBlocking { ... }
, the return type of main is inferred to be whatever
runBlocking
returns. You can use an explicit
Unit
instead, or use a block body instead of an expression body.
πŸ‘ 1
e
you can write
Copy code
fun main(): Unit = runBlocking { ... }
or
Copy code
fun main() {
    runBlocking { ... }
}
or
Copy code
fun main() = runBlocking<Unit> { ... }
βž• 2
πŸ‘ 1
l
It works : thank you very much πŸ™‚
e
but if you're targeting JVM I would simply write
Copy code
suspend fun main(): Unit {
    ...
}
the Kotlin compiler will put in a simple event loop to bridge to Java-like
main
πŸ‘Œ 1
πŸ‘ 1
j
Also, for posterity, the message
No main method found in project
really means that Kotlin didn't find a method that matches the expected signature of a
main
method. Even though you do have a
main()
function, it doesn't conform to the expected signature of a main function (which required returning
Unit
)
πŸ‘ 1
l
Also, I'm wondering why the two print statements still happens at the end of the execution of the runBLocking, and why the first print statement is not printed immediately. (Hence the two launch call, that was my attempt)
j
I'm not 100% sure I understand your question. What exactly is the behavior you would expect? And what do you get instead?
l
What I want to achieve is that the line "I'm starting" is printed immediately, and then the line "I'm done" after some milliseconds.
j
What you expect is what would happen in real life, but the playground probably buffers the output and sends it in one go
πŸ‘ 1
gratitude thank you 1
l
Ok I understand better πŸ™‚
j
If you want to experiment with timings, you're probably better off running this stuff on your local machine πŸ˜‰
l
Yes you're right πŸ™‚
I've just opened a fresh Kotlin project in Idea Community, but I can't find how to add a package : so should I create another type of project or is it possible with this one ?
j
The way to add dependencies (such as coroutines) to your project depends on your build system. If you used the IDEA new project wizard, there should have been some option to choose the build system. The most common build system for Kotlin projects is currently Gradle. Is this the one you had selected?
l
Oups ! I think I miss that build system ...
I'll try to add Gradle.
πŸ‘ 1
Done, I confirm that the behaviour from my snippet is the correct one inside Idea πŸ™‚ Thank you very much for your help.
πŸ†’ 1