I'm playing with coroutines, trying to round out/b...
# getting-started
t
I'm playing with coroutines, trying to round out/better understand them instead of skirting around them. reading through the docs (https://kotlinlang.org/docs/coroutines-basics.html#scope-builder) and playing with variations in the online playground, I found that if I do this:
Copy code
fun main() = runBlocking {
    launch { foo("a", 2) }
    launch { foo("b", 3) }
}
I get a "No main method found in project" error. But if I add a
println
statement then things work?
Copy code
fun main() = runBlocking {
    launch { foo("a", 2) }
    launch { foo("b", 3) }
    println("tada")
}
I can put that anywhere (top, middle, last) for it to make it so I don't get the "No main method" error. If I try a different statement, such as just a
3 + 4
, I get the same error. But if I store it in a variable (e.g.
val total = 3  + 4
) , then it works. What's going on here? Is this something to do with the Playground? or a nuance of
runBlocking
? Or something else?
y
launch
returns a
Job
object, which allows you to manually cancel that launched coroutine.
runBlocking
returns whatever your block returns. So you end up with a
fun main(): Job
, which won't run since the expectation is that your main method returns
Unit
.
println
returns Unit. What you can do is simply annotate it
fun main(): Unit = runBlocking {}
Nothing to do with coroutines and all to do with type inference and expression blocks for functions
🙏 1
j
you can do
suspend fun main
which I think it is sugar to the run blocking method
y
IIRC
suspend fun main
is ever so slightly different than
runBlocking
(it doesn't even rely on coroutines lol) but I think it is considered "better" than
runBlocking
t
I went with the Unit annotation. Subtle that, and I learned something. Just the reason I decided to sort of go back to the basics, read the docs thoroughly, and sort of play with it all from all sides. Thanks
c
In IntelliJ, I highly recommend enabling inlay hints in the settings, they show the type inference information directly in the code, which makes it much easier to understand these cases.
☝️ 4