Kotlinc include other jar files

523 views Asked by At

I would like to run an app from the command line on MacOS. The problem is that I want to include Gson in the file to convert my data classes into a json object. (I'm new to command line with kotlin)

To simplify, I use the following:

fun main() {
    val item = Building(1, "Name", 4, 2)

    val jsonBuilding: String = Gson().toJson(item)
}

To create/run my code in the command line I use:

>> kotlinc creator.kt -include-runtime -d creator.jar

>> java -jar creator.jar

Now my question is how to include the gson.jar to be able to use it into the app?

Currently, I receive errors because it cannot resolve the Gson():

creator.kt:37:16: error: unresolved reference: Gson
   val gson = Gson()

Any help is appreciated.

1

There are 1 answers

0
Ioannis Tzavaras On BEST ANSWER

You probably use Intellj IDEA. When you make a JVM Gradle command line app you should and the follow code on build.gradle.kts file.

tasks.withType<Jar> {
manifest {
    attributes["Main-Class"] = "com.your_project_package.MainKt"
}
// To add all of the dependencies
from(sourceSets.main.get().output)

dependsOn(configurations.runtimeClasspath)
from({
    configurations.runtimeClasspath.get().filter { it.name.endsWith("jar") }.map { zipTree(it) }
})
}

Then build your project and from gradle tasks you should find Tasks->build->jar click it and that's all. You have your jar file in you project folder, build->libs->project.jar.

Now you can run your jar file as java jar file with the follow command:

java -jar your_project_package.jar

exemple

I hope that's helpful for you