Jar file only works with Java classes but not with Kotlin

Sure. Let’s suppose the JAR you want to create is called ``minimalkotlin.jar```.

When you’re running that JAR through java -jar minimalkotlin.jar the following happens:

  1. The command java looks into the JAR file into META-INF/MANIFEST.MF because it needs to find out which class it is supposed to run (as you didn’t specify a class to run explicitely). There’s a property Main-Class in that file that tells it what the main entry point for that JAR is.
  2. Then, it tries to locate the main class as specified in the JAR
  3. That class references quite a few other classes (because your Kotlin application is referencing classes from the Kotlin runtime internally). That Kotlin runtime basically does all the internal stuff (parameter checks, mapping function names, …)
  4. As a consequence, java has to find those Kotlin runtime classes as well. Unfortunately, it can’t do that if you put a kotlin-runtime.jar into your JAR file. It simply doesn’t know how to handle JAR libraries within another JAR file. (I simplified a little bit here but that should do the trick for now)

In order for java to find those Kotlin runtime classes, the contents of kotlin-reflect.jar and kotlin-runtime.jar need to be present in your JAR. Basically, IDEA is unzipping those two files and dumping their content into what will become your JAR (first two entries in my screenshot). Then IDEA adds the compiler output of your own code (third entry in screenshot).

That KotlinJavaRuntime (Project Library) is automatically generated when you create a new Kotlin project. Basically, it is a container that holds all the JAR files that belong to the Kotlin runtime. You should be able to see it in File > Project Structure and then select Libraries on the left hand side of the dialog. You’ll see that it contains two JARs with binaries and one that holds source code (which will be used when you navigate to the source of a Kotlin runtime class).

If that KotlinJavaRuntime (Project Library) entry is not there (and as a consequence, you are not able to run or compile any Kotlin code from within IDEA itself!), you need to fix that before setting up JAR creation. I believe Tools > Kotlin > Configure Kotlin in Project should do the trick. After that, the Kotlin runtime library object should be available as described above.

Just follow the steps in my other post to set up how IDEA creates your JAR file. Let me know if that helps!

1 Like