kotlin coroutines don't work in a command line

61 Views Asked by At

I have the following program:

//Main.kt
import kotlinx.coroutines.*
import java.util.concurrent.*

fun main() {
        val scope = CoroutineScope(Job() + Dispatchers.Default)

        scope.launch{
                println("hello")
        }
}

I tried to run it in a command line:

i@LAPTOP:/mnt/d/PROJECTS$ ls
Main.kt  annotations-23.0.0.jar  kotlin-stdlib-1.9.21.jar  kotlinx-coroutines-core-jvm-1.8.0-RC2.jar
i@LAPTOP:/mnt/d/PROJECTS$ kotlinc Main.kt -cp annotations-23.0.0.jar:kotlin-stdlib-1.9.21.jar:kotlinx-coroutines-core-jvm-1.8.0-RC2.jar
i@LAPTOP:/mnt/d/PROJECTS$ java -cp annotations-23.0.0.jar:kotlin-stdlib-1.9.21.jar:kotlinx-coroutines-core-jvm-1.8.0-RC2.jar:. MainKt
i@LAPTOP:/mnt/d/PROJECTS$

I expected to see hello in the command line but for some reason my program prints nothing. Why?

1

There are 1 best solutions below

0
broot On

This is because you launched the coroutine in the background and immediately finished running your application, so the coroutine didn't even have a chance to start executing.

If you want to wait for the coroutine to finish, use runBlocking instead of launch:


fun main() {
    runBlocking {
        println("hello")
    }
}

You can also simply do Thread.sleep(1000) after launching, but generally we shouldn't assume an asynchronous task will take a specific amount of time.