Home > Software engineering >  How to compile and run Kotlin code involing coroutines on Windows
How to compile and run Kotlin code involing coroutines on Windows

Time:09-28

I want to study Kotlin coroutines more, but sometimes to lazy to debug on Android phone, so prefer PC instead.

Here's a sample code:

import kotlinx.coroutines.*

fun main() = runBlocking { // this: CoroutineScope
    launch { // launch a new coroutine and continue
        delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
        println("World!") // print after delay
    }
    println("Hello") // main coroutine continues while a previous one is delayed
}

Let's compile it:

kotlinc CoMain01.kt -cp C:\kotlin\lib\kotlinx-coroutines-core-jvm.jar -include-runtime -d CoMain01.jar

Seems OK. CoMain01.jar is generated and no error message/warning. The unsolved question is: how to run the jar?

java -jar -cp C:\kotlin\lib\kotlinx-coroutines-core-jvm.jar CoMain01.jar

java -cp C:\kotlin\lib\kotlinx-coroutines-core-jvm.jar CoMain01.jar

don't work. Same error message:

Error: Could not find or load main class CoMain01.jar Caused by: java.lang.ClassNotFoundException: CoMain01.jar

I'm on Windows 10 with OpenJDK Runtime Environment Corretto-11.0.12.7.1 and Kotlin 1.5.30 (on C:\Kotlin) installed.

Any help/information is appreciated.

CodePudding user response:

You need to specify both jars on your classpath, and then give the name of the main class to run as argument.

The main class is named based on the file containing the main() method. If your file is main.kt, then the main class name will be MainKt. In that case the following should work:

java -cp "C:\kotlin\lib\kotlinx-coroutines-core-jvm.jar;CoMain01.jar" MainKt

But honestly using an IDE would be more practical for little local experiments :)

  • Related