Part 16 / Topic 1 of 5
Packaging a runnable CLI as a jar
kotlinc alone can turn one .kt file into a .jar that runs anywhere a JVM does, with no
separate install step for the person running it.
fun applyGst(amountInr: Double, ratePercent: Int = 18): Double =
amountInr + (amountInr * ratePercent / 100.0)
fun main(args: Array<String>) {
if (args.isEmpty()) {
println("usage: gstcalc <amountInr> [ratePercent]")
return
}
val amount = args[0].toDoubleOrNull() ?: return println("not a number: ${args[0]}")
val rate = if (args.size > 1) args[1].toIntOrNull() ?: 18 else 18
println("Rs.%.2f + %d%% GST = Rs.%.2f".format(amount, rate, applyGst(amount, rate)))
}
$ kotlinc 01_packaging_as_a_jar.kt -include-runtime -d gstcalc.jar
$ java -jar gstcalc.jar 1000
Rs.1000.00 + 18% GST = Rs.1180.00
$ java -jar gstcalc.jar 2000 12
Rs.2000.00 + 12% GST = Rs.2240.00
$ java -jar gstcalc.jar
usage: gstcalc <amountInr> [ratePercent]
-include-runtime bundles the Kotlin standard library inside the jar, which is why the jar is
a real ~5.4 MB instead of a few kilobytes -- and why java -jar gstcalc.jar works on a machine
that has a JVM but no Kotlin installed at all. Leave it off, and you get a tiny jar that fails:
$ kotlinc 01_packaging_as_a_jar.kt -d gstcalc-slim.jar
$ ls -lh gstcalc.jar gstcalc-slim.jar
5.4M gstcalc.jar
1.9K gstcalc-slim.jar
$ java -jar gstcalc-slim.jar 1000
Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics
Every Kotlin program calls into the standard library (here, just for a null check on the
args[0] parameter) -- without -include-runtime, that library has to be on the classpath some
other way:
$ java -cp "gstcalc-slim.jar:/opt/homebrew/Cellar/kotlin/2.4.21/libexec/lib/kotlin-stdlib.jar" _01_packaging_as_a_jarKt 1000
Rs.1000.00 + 18% GST = Rs.1180.00
(The class name has a leading underscore -- _01_packaging_as_a_jarKt, not
01_packaging_as_a_jarKt -- for the exact filename-starting-with-a-digit reason Part 15,
section 1 covered. A normal filename like GstCalculator.kt would make GstCalculatorKt.)
-include-runtime makes that classpath juggling unnecessary, which is why every jar in this
part uses it. kotlinc also picked the entry point for you -- java -jar needs to know which
class has main, and that's written into the jar's manifest automatically:
$ unzip -p gstcalc.jar META-INF/MANIFEST.MF
Manifest-Version: 1.0
Created-By: JetBrains Kotlin
Main-Class: _01_packaging_as_a_jarKt
Full program: examples/01_packaging_as_a_jar.kt.
Done here? The practice set for Part 16 — including the solutions — is on the part page.