6

I am trying kotlin for the first time.

I was able to run compile the hello world program in kotlin on command line but I am not able to compile program where I want to include external java library

import com.google.gson.Gson

data class Person(val name: String, val age: Int, val gender: String?)

fun main(args: Array<String>) {
    println("Hello world");
    val gson = Gson()
    val person = Person("navin", 30, null)
    val personJson = gson.toJson(person)
    println(personJson)
}

Directory structure

➜  kotlin tree
.
├── gson.jar
├── json.jar
└── json.kt

0 directories, 3 files
➜  kotlin 

Code compilation works fine but I am not able to run the program

➜  kotlin kotlinc -classpath gson.jar json.kt -include-runtime -d json.jar
➜  kotlin java -jar json.jar -cp gson.jar                                 
Hello world
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/gson/Gson
        at JsonKt.main(json.kt:7)
Caused by: java.lang.ClassNotFoundException: com.google.gson.Gson
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 1 more
➜  kotlin 

Need help understanding how to run the above program.

navin
  • 165
  • 1
  • 12

2 Answers2

4

When you use -jar, the -cp argument is ignored, so you can't specify any additional dependencies. Instead, you need to specify both jars in the -cp argument:

java -cp json.jar:gson.jar JsonKt
yole
  • 92,896
  • 20
  • 260
  • 197
0

to run from command line, Kotlin program which is using external library for compile :

kotlinc -cp "C:\Users\<user>\Desktop\kotlin\programs\gson-2.10.jar" GsonTest.kt

for run:

kotlin -cp ".;C:\Users\<user>\Desktop\kotlin\programs\gson-2.10.jar" GsonTestKt

note: please give full path location for external jar's as mention above, user will be your system name.

Mohd Qasim
  • 896
  • 9
  • 20