QuantumZ
QuantumZ

Reputation: 41

NoClassDefFoundError caused by Kotlin readLine function

Whenever i try to execute a .jar file containing my code, it throws NoClassDefFoundError: kotlin/io/ConsoleKt. So far i haven't found a solution to this problem but I think the problem has something to do with the readLine() function I have in the script but I don't know what. The weird thing is that my code ran perfectly in Intellij itself but once I built it started throwing this exception that never happened outside of IntelliJ. The specific error is:

Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/io/ConsoleKt
        at com.quantumzizo.calcualtorkotlin.DisplayKt.main(Display.kt:23)
        at com.quantumzizo.calcualtorkotlin.DisplayKt.main(Display.kt)
Caused by: java.lang.ClassNotFoundException: kotlin.io.ConsoleKt
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
        ... 2 more

Is there solution that can solve this?

Upvotes: 0

Views: 677

Answers (2)

user13482411
user13482411

Reputation: 331

As mentioned, the solution is to bundle the Kotlin stdlib into the .jar file. kotlin.io is implicitly imported into the Kotlin code so the compilation finishes without errors, but at runtime java can't find the missing bytecode. Specifically the file kotlin/io/ConsoleKt.class holds the bytecode for the readLine() function.

I'd just like to extend the accepted answer for us who often directly invoke the Kotlin compiler. You need the -include-runtime option, so e.g.

kotlinc -include-runtime -d kotlin_app.jar

You can tell that the runtime is included if the file size of the jar (for a small program) is ~5MB, compared to ~1KB without the runtime.

Upvotes: 0

QuantumZ
QuantumZ

Reputation: 41

So it turns out all I had to do was build a fat jar with all the dependencies. I used the Gradle plugin Shadow to make a fat jar. Props to @Endzeit for suggesting that I use it.

Upvotes: 3

Related Questions