I’m new to Kotlin so maybe this is a dumb question, but I found nothing about this issue on the internet. My question is how to use kotlinx
packages (like coroutine functions) when compiling the file with the normal kotlinc compiler. I’m compiling my program with
kotlinc main.kt
and when I try to
import kotlinx.coroutines.*
I get the following error message:
error: unresolved reference: kotlinx
Do I have to call the compiler with any different arguments or install something? Or do I have to use another build system like Gradle?
It is very much a pain to do it completely on the command line. I highly recommend using Gradle/Maven instead.
First, you need to download the coroutines jar - this is not part of the standard library. Here is the page for that on Maven. Let's say you want version 1.9.0. You'd download kotlinx-coroutines-core-jvm-1.9.0.jar from here.
Then let's make a very simple example Main.kt file
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() =
runBlocking {
launch {
delay(1000)
println("Kotlin Coroutines World!")
}
println("Hello")
}
You can compile this to a .jar using the coroutines jar as the class path.
kotlinc -cp kotlinx-coroutines-core-jvm-1.9.0.jar Main.kt -include-runtime -d output.jar
Then you can run the MainKt
class inside output.jar using both output.jar and the coroutines jar as the class path. Note the class path separator here - ;
on Windows and :
on macOS/Linux.
java -cp kotlinx-coroutines-core-jvm-1.9.0.jar:output.jar MainKt
Theoretically, it should also work if you run the jar directly with java -jar
, but that doesn't work for some reason...
At the end of the day, just use Gradle, which does practically everything for you. All you need to do is to add
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
}
in build.gradle.kts.