Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 16 / Stage 3

Packaging and modern Kotlin

Goal: Package a Kotlin program as a runnable .jar with plain kotlinc -- no Gradle -- lay out a small CLI across more than one file the same way a Gradle project would, know exactly when that stops scaling and what Part 11's Gradle path buys you, and get an honest, locally-verified tour of value classes and a handful of genuinely new Kotlin language features. Time: ~4 hours · Level: comfortable with Part 9's classes, Part 11's project layout, and Part 15's internals

🔍 Going deeper: everything below was compiled and run for real with kotlinc-jvm 2.4.21 (JRE 21.0.11+10-LTS) (see ../../TOOLING.md). Part 11's own README confirms this machine has kotlinc and JDK 21 but not Gradle (which gradle and gradle -v both came back empty) -- this part deliberately stays on the Gradle-free side of that line, and points at Part 11 for what a real build tool adds once a project outgrows it.

What you will learn

  • Packaging a single Kotlin file as a standalone, runnable .jar with kotlinc -include-runtime -d app.jar, what's actually inside that jar, and what breaks (and why) without -include-runtime
  • Laying a small CLI out across more than one file -- the same src/main/kotlin/<package>/... shape Part 11's Gradle project uses -- and compiling it with plain kotlinc, two ways
  • Exactly where loose files + kotlinc stop scaling, and what Part 11's Gradle setup buys you once they do: a test framework dependency, src/test/kotlin, ./gradlew build
  • A locally-verified (not memorized) tour of newer Kotlin language features: entries, data object, guard conditions in when, multi-dollar string templates, and context parameters
  • Value classes (@JvmInline value class): type-safe wrappers with little to no runtime cost, confirmed with the same javap/reflection techniques Part 15 taught
  • Mini-build: splitbill, your own multi-file CLI tool, packaged and run as a standalone .jar

Topics in this part

Practice

Exercises 1–2 ask you to actually package and run a jar, the same way the README's sections 1 and 2 do — "sample output" there means a real terminal transcript with kotlinc/java -jar. Exercises 3–8 are plain main() programs, like every other part.


Exercise 1: Package a UPI limit checker as a jar

Scenario: A quick CLI that tells you how much of today's ₹1,00,000 UPI limit is left, handed to someone who doesn't have Kotlin installed at all — it has to run on a bare JVM. What to do: Write fun remainingLimit(usedInr: Double, dailyLimitInr: Double = 100000.0): Double returning (dailyLimitInr - usedInr).coerceAtLeast(0.0), and a main(args: Array<String>) that prints a usage message with no args, "not a number: ..." for bad input, otherwise "Remaining UPI limit today: Rs.%.2f". Compile it with -include-runtime into a jar and run it with java -jar three times: ₹65,000 used, ₹1,50,000 used (over the limit), and no arguments.

Sample output:

$ kotlinc ex01.kt -include-runtime -d ex01.jar
$ java -jar ex01.jar 65000
Remaining UPI limit today: Rs.35000.00
$ java -jar ex01.jar 150000
Remaining UPI limit today: Rs.0.00
$ java -jar ex01.jar
usage: walletlimit <usedInr>

💡 Hint: coerceAtLeast(0.0) is what keeps an over-the-limit input from printing a negative "remaining" amount.


Exercise 2: A shipping-fee CLI, split across two files

Scenario: The same kind of tiny CLI as section 2's billcalc, but for shipping fees, laid out as two files under one package and compiled with plain kotlinc — no jar, no Gradle. What to do: Under src/main/kotlin/com/stepshala/shippingcli/, write Shipping.kt with fun shippingFeeInr(weightKg: Double): Double (<= 1.0 kg → 40.0, <= 5.0 kg → 70.0, else 120.0), and Main.kt with a main(args: Array<String>) that prints the fee for the given weight (or a usage message with no args). Compile the whole src/main/kotlin directory with -include-runtime into one jar, and run it for 0.5, 3.0, and 10.0 kg.

Sample output:

$ kotlinc src/main/kotlin -include-runtime -d shippingcli.jar
$ java -jar shippingcli.jar 0.5
Shipping fee for 0.5kg: Rs.40.00
$ java -jar shippingcli.jar 3.0
Shipping fee for 3.0kg: Rs.70.00
$ java -jar shippingcli.jar 10.0
Shipping fee for 10.0kg: Rs.120.00
$ unzip -p shippingcli.jar META-INF/MANIFEST.MF | grep Main-Class
Main-Class: com.stepshala.shippingcli.MainKt

💡 Hint: the package declaration at the top of both files (package com.stepshala.shippingcli) is what makes Main-Class come out package-qualified.


Exercise 3: Type-safe PAN and Aadhaar wrappers

Scenario: A KYC form handles a PAN and the last four digits of an Aadhaar number as two separate String fields — easy to pass in the wrong order by accident, which value classes should make impossible. What to do: Write @JvmInline value class PanNumber(val value: String) validating against Regex("[A-Z]{5}[0-9]{4}[A-Z]") in init, and @JvmInline value class AadhaarLast4(val value: String) validating "exactly 4 digits" in init. Write fun maskedProfile(pan: PanNumber, aadhaarLast4: AadhaarLast4): String. In main(), call it with a valid pair and print the result; try an invalid PAN and an invalid Aadhaar suffix inside runCatching { }, printing each caught message; then use Class.forName("...").declaredMethods (as Part 15's exercise 8 did) to print maskedProfile's real JVM parameter types and whether its JVM method name is mangled (not exactly "maskedProfile").

Sample output:

PAN ABCDE1234F, Aadhaar ending 4321
bad PAN rejected: invalid PAN: abc123
bad Aadhaar suffix rejected: invalid Aadhaar suffix: 12a4
maskedProfile()'s real JVM parameter types: [String, String]
maskedProfile()'s JVM name is mangled: true

💡 Hint: the class name to pass to Class.forName(...) is your file's generated FileNameKt name — if your file starts with a digit, remember Part 15/16's leading-underscore rule.


Exercise 4: Delivery routing with data object and entries

Scenario: A delivery router assigns a slot and an agent, or reports that nobody is free — "nobody is free" needs no data of its own, which is exactly what data object is for. What to do: Write enum class DeliverySlot { MORNING, AFTERNOON, EVENING, NIGHT } and sealed interface RouteResult with data class Assigned(val slot: DeliverySlot, val agent: String) : RouteResult and data object NoAgentsAvailable : RouteResult. Write fun describe(result: RouteResult): String. In main(), print DeliverySlot.entries and its size, describe one Assigned result and NoAgentsAvailable, and print whether NoAgentsAvailable === NoAgentsAvailable.

Sample output:

all slots: [MORNING, AFTERNOON, EVENING, NIGHT]
slot count: 4
EVENING delivery assigned to Ravi Kumar
no agents available right now
NoAgentsAvailable is a singleton: true

💡 Hint: when over a sealed interface can match NoAgentsAvailable directly, by name, with no is — it's a single object, not a type with instances.


Exercise 5: Shipping and shape rules with guard conditions

Scenario: Two unrelated rule tables — free shipping tiers, and a shape classifier — both read far more clearly as one flat list of conditions than as nested ifs inside a when. What to do: Write data class Customer(val name: String, val isPrime: Boolean) and data class Order(val amountInr: Double, val customer: Customer), then fun shippingLabel(order: Order): String using a condition-only when (no subject) for: prime + >= 500.0 → "FREE express shipping"; prime alone → "FREE standard shipping"; >= 1000.0 → "FREE standard shipping (bulk order)"; else → "Rs.49.00 shipping". Separately, write sealed interface Shape with Circle(radiusCm)/Rect(wCm, hCm), and fun shapeLabel(shape: Shape): String using guard conditions (is Circle if ...) to label a circle as "large" above 20cm radius, a Rect with equal sides as "square," and an oversized Rect (either side over 100cm) as "oversized rectangle." Try all the boundary cases in main().

Sample output:

FREE express shipping
FREE standard shipping
FREE standard shipping (bulk order)
Rs.49.00 shipping
large circle
circle
square
oversized rectangle
rectangle

💡 Hint: guard-condition branches are checked in order, same as any when — put the more specific condition (is Rect if shape.wCm == shape.hCm, a square) before the more general oversized check, or a 150×150 square would hit "oversized" first.


Exercise 6: A context-parameter currency formatter

Scenario: The same priceTagUsd formatting logic needs to run under whichever exchange rate is current, without threading a rate parameter through every call by hand. What to do: Write interface ExchangeRate { fun toUsd(amountInr: Double): Double } and class FixedRate(private val inrPerUsd: Double) : ExchangeRate. Write context(rate: ExchangeRate) fun priceTagUsd(amountInr: Double): String returning "Rs.%.2f = $%.2f". In main(), call priceTagUsd for ₹830 under an 83.0 rate and for ₹880 under an 88.0 rate (each inside its own with(rate) { }), then run a List of three amounts through priceTagUsd all under the 83.0 rate with a single with(marchRate) { amounts.forEach { ... } }.

Sample output:

Rs.830.00 = $10.00
Rs.880.00 = $10.00
Rs.415.00 = $5.00
Rs.830.00 = $10.00
Rs.1660.00 = $20.00

💡 Hint: priceTagUsd(830.0) is the entire call — there is no second argument for the rate anywhere in the call site; it only compiles inside a with(someRate) { } block (or any other scope that puts an ExchangeRate in context).


Exercise 7: A receipt template with multi-dollar strings

Scenario: A receipt template needs to show a customer's order id and amount interpolated for real, and separately show the literal placeholder text ("$orderId", "$amountInr") as part of a help note — in the same string, without one meaning fighting the other. What to do: Write fun receipt(orderId: String, amountInr: Double): String returning a multi-dollar ($$"""...""") triple-quoted string with |-prefixed lines (use .trimMargin()): one line interpolating orderId and amountInr with $$, and a note line that shows the literal text "$orderId" and "$amountInr" (a single $, not interpolated) followed by those same two values genuinely interpolated again, on the same line. Call it from main() with "ORD-8841" and 1499.0.

Sample output:

Order ORD-8841
Amount: Rs.1499.0
Note: the receipt template literally contains the text "$orderId" and "$amountInr"
      as placeholders in some systems -- this string can show that text AS TEXT,
      not interpolated, right here: $orderId $amountInr

💡 Hint: inside a $$"..." string, $$name interpolates and a bare $name is literal text — that's the entire trick, the opposite of an ordinary "$name" string where a literal $ needs its own escape.


Exercise 8: Extend the mini-build with a new subcommand, packaged

Scenario: splitbill (the README's mini-build) needs a third command: split a bill with a tip added first, not just a plain GST/split — built as a proper multi-file CLI and packaged as a jar, like the real thing. What to do: Under src/main/kotlin/com/stepshala/tipcli/, write Money.kt with the same RupeesPaise value class as the README's mini-build plus fun withTip(amount: RupeesPaise, tipPercent: Int): RupeesPaise, Command.kt with a sealed class Command (Tip(amount, tipPercent, people), Help, Invalid(reason)), a parse(args) and a run(command) using a guard condition for the one-person case (same pattern as the README's Split), and Main.kt's fun main(args: Array<String>). Compile the directory into a jar and run it for: a 4-way split with a 10% tip, a 1-person "split," a people = 0 error, and help.

Sample output:

$ kotlinc src/main/kotlin -include-runtime -d tipcli.jar
$ java -jar tipcli.jar tip 1000 10 4
Total with 10% tip: Rs.1100.00, split 4 ways: Rs.275.00 each
$ java -jar tipcli.jar tip 500 15 1
One person pays the full Rs.575.00
$ java -jar tipcli.jar tip 900 10 0
Error: people must be at least 1, got 0
$ java -jar tipcli.jar help
usage: tipcli tip <amountInr> <tipPercent> <people>

💡 Hint: withTip belongs in Money.kt next to RupeesPaise, the same way the README's applyGst sits next to it — keep money math and command parsing in separate files.

Show the solutions for Part 16 (11 files)

solutions/ex01.kt

fun remainingLimit(usedInr: Double, dailyLimitInr: Double = 100000.0): Double =
    (dailyLimitInr - usedInr).coerceAtLeast(0.0)

fun main(args: Array<String>) {
    if (args.isEmpty()) {
        println("usage: walletlimit <usedInr>")
        return
    }
    val used = args[0].toDoubleOrNull()
    if (used == null) {
        println("not a number: ${args[0]}")
        return
    }
    println("Remaining UPI limit today: Rs.%.2f".format(remainingLimit(used)))
}

solutions/ex02-project/src/main/kotlin/com/stepshala/shippingcli/Main.kt

package com.stepshala.shippingcli

fun main(args: Array<String>) {
    if (args.isEmpty()) {
        println("usage: shippingcli <weightKg>")
        return
    }
    val weight = args[0].toDoubleOrNull() ?: return println("not a number: ${args[0]}")
    println("Shipping fee for ${weight}kg: Rs.%.2f".format(shippingFeeInr(weight)))
}

solutions/ex02-project/src/main/kotlin/com/stepshala/shippingcli/Shipping.kt

package com.stepshala.shippingcli

fun shippingFeeInr(weightKg: Double): Double = when {
    weightKg <= 1.0 -> 40.0
    weightKg <= 5.0 -> 70.0
    else -> 120.0
}

solutions/ex03.kt

@JvmInline
value class PanNumber(val value: String) {
    init { require(Regex("[A-Z]{5}[0-9]{4}[A-Z]").matches(value)) { "invalid PAN: $value" } }
}

@JvmInline
value class AadhaarLast4(val value: String) {
    init { require(value.length == 4 && value.all { it.isDigit() }) { "invalid Aadhaar suffix: $value" } }
}

fun maskedProfile(pan: PanNumber, aadhaarLast4: AadhaarLast4) =
    "PAN ${pan.value}, Aadhaar ending ${aadhaarLast4.value}"

fun main() {
    println(maskedProfile(PanNumber("ABCDE1234F"), AadhaarLast4("4321")))

    val badPan = runCatching { PanNumber("abc123") }.exceptionOrNull()
    println("bad PAN rejected: ${badPan?.message}")

    val badAadhaar = runCatching { AadhaarLast4("12a4") }.exceptionOrNull()
    println("bad Aadhaar suffix rejected: ${badAadhaar?.message}")

    val method = Class.forName("Ex03Kt").declaredMethods.first { it.name.startsWith("maskedProfile") }
    println("maskedProfile()'s real JVM parameter types: ${method.parameterTypes.map { it.simpleName }}")
    println("maskedProfile()'s JVM name is mangled: ${method.name != "maskedProfile"}")
}

solutions/ex04.kt

enum class DeliverySlot { MORNING, AFTERNOON, EVENING, NIGHT }

sealed interface RouteResult
data class Assigned(val slot: DeliverySlot, val agent: String) : RouteResult
data object NoAgentsAvailable : RouteResult

fun describe(result: RouteResult): String = when (result) {
    is Assigned -> "${result.slot} delivery assigned to ${result.agent}"
    NoAgentsAvailable -> "no agents available right now"
}

fun main() {
    println("all slots: ${DeliverySlot.entries}")
    println("slot count: ${DeliverySlot.entries.size}")

    println(describe(Assigned(DeliverySlot.EVENING, "Ravi Kumar")))
    println(describe(NoAgentsAvailable))
    println("NoAgentsAvailable is a singleton: ${NoAgentsAvailable === NoAgentsAvailable}")
}

solutions/ex05.kt

data class Customer(val name: String, val isPrime: Boolean)
data class Order(val amountInr: Double, val customer: Customer)

fun shippingLabel(order: Order): String = when {
    order.customer.isPrime && order.amountInr >= 500.0 -> "FREE express shipping"
    order.customer.isPrime -> "FREE standard shipping"
    order.amountInr >= 1000.0 -> "FREE standard shipping (bulk order)"
    else -> "Rs.49.00 shipping"
}

sealed interface Shape
data class Circle(val radiusCm: Double) : Shape
data class Rect(val wCm: Double, val hCm: Double) : Shape

fun shapeLabel(shape: Shape): String = when (shape) {
    is Circle if shape.radiusCm > 20.0 -> "large circle"
    is Circle -> "circle"
    is Rect if shape.wCm == shape.hCm -> "square"
    is Rect if shape.wCm > 100.0 || shape.hCm > 100.0 -> "oversized rectangle"
    is Rect -> "rectangle"
}

fun main() {
    val prime = Customer("Asha", isPrime = true)
    val regular = Customer("Ravi", isPrime = false)

    println(shippingLabel(Order(600.0, prime)))
    println(shippingLabel(Order(200.0, prime)))
    println(shippingLabel(Order(1200.0, regular)))
    println(shippingLabel(Order(300.0, regular)))

    println(shapeLabel(Circle(25.0)))
    println(shapeLabel(Circle(5.0)))
    println(shapeLabel(Rect(10.0, 10.0)))
    println(shapeLabel(Rect(150.0, 20.0)))
    println(shapeLabel(Rect(10.0, 20.0)))
}

solutions/ex06.kt

interface ExchangeRate { fun toUsd(amountInr: Double): Double }

context(rate: ExchangeRate)
fun priceTagUsd(amountInr: Double): String = "Rs.%.2f = $%.2f".format(amountInr, rate.toUsd(amountInr))

class FixedRate(private val inrPerUsd: Double) : ExchangeRate {
    override fun toUsd(amountInr: Double) = amountInr / inrPerUsd
}

fun main() {
    val marchRate = FixedRate(83.0)
    val novemberRate = FixedRate(88.0)

    with(marchRate) {
        println(priceTagUsd(830.0))
    }
    with(novemberRate) {
        println(priceTagUsd(880.0))
    }

    // Same amount, two different rates in context -- priceTagUsd itself never takes a rate parameter.
    val amounts = listOf(415.0, 830.0, 1660.0)
    with(marchRate) {
        amounts.forEach { println(priceTagUsd(it)) }
    }
}

solutions/ex07.kt

fun receipt(orderId: String, amountInr: Double): String {
    return $$"""
        |Order $$orderId
        |Amount: Rs.$$amountInr
        |Note: the receipt template literally contains the text "$orderId" and "$amountInr"
        |      as placeholders in some systems -- this string can show that text AS TEXT,
        |      not interpolated, right here: $orderId $amountInr
    """.trimMargin()
}

fun main() {
    println(receipt("ORD-8841", 1499.0))
}

solutions/ex08-project/src/main/kotlin/com/stepshala/tipcli/Command.kt

package com.stepshala.tipcli

sealed class Command {
    data class Tip(val amount: RupeesPaise, val tipPercent: Int, val people: Int) : Command()
    data object Help : Command()
    data class Invalid(val reason: String) : Command()
}

fun parse(args: Array<String>): Command {
    if (args.isEmpty() || args[0] == "help") return Command.Help
    if (args[0] != "tip") return Command.Invalid("unknown command: ${args[0]}")
    if (args.size != 4) return Command.Invalid("usage: tipcli tip <amountInr> <tipPercent> <people>")
    val amount = args[1].toDoubleOrNull() ?: return Command.Invalid("not a number: ${args[1]}")
    val tipPercent = args[2].toIntOrNull() ?: return Command.Invalid("not a number: ${args[2]}")
    val people = args[3].toIntOrNull() ?: return Command.Invalid("not a number: ${args[3]}")
    if (people <= 0) return Command.Invalid("people must be at least 1, got $people")
    return Command.Tip(RupeesPaise.fromRupees(amount), tipPercent, people)
}

fun run(command: Command): String = when (command) {
    is Command.Tip if command.people == 1 -> "One person pays the full ${withTip(command.amount, command.tipPercent)}"
    is Command.Tip -> {
        val total = withTip(command.amount, command.tipPercent)
        "Total with ${command.tipPercent}% tip: $total, split ${command.people} ways: ${total / command.people} each"
    }
    is Command.Invalid -> "Error: ${command.reason}"
    Command.Help -> "usage: tipcli tip <amountInr> <tipPercent> <people>"
}

solutions/ex08-project/src/main/kotlin/com/stepshala/tipcli/Main.kt

package com.stepshala.tipcli

fun main(args: Array<String>) {
    println(run(parse(args)))
}

solutions/ex08-project/src/main/kotlin/com/stepshala/tipcli/Money.kt

package com.stepshala.tipcli

@JvmInline
value class RupeesPaise(val paise: Long) {
    init { require(paise >= 0) { "amount cannot be negative, got $paise paise" } }
    operator fun plus(other: RupeesPaise) = RupeesPaise(paise + other.paise)
    operator fun div(parts: Int) = RupeesPaise(paise / parts)
    override fun toString() = "Rs.%d.%02d".format(paise / 100, paise % 100)

    companion object {
        fun fromRupees(amount: Double) = RupeesPaise((amount * 100).toLong())
    }
}

fun withTip(amount: RupeesPaise, tipPercent: Int): RupeesPaise =
    RupeesPaise(amount.paise + (amount.paise * tipPercent) / 100)

Common mistakes

Mistake Why it is wrong Fix
Forgetting -include-runtime and being surprised by NoClassDefFoundError Every Kotlin program depends on the standard library; a plain kotlinc -d app.jar doesn't bundle it Use kotlinc ... -include-runtime -d app.jar for anything meant to run standalone
Assuming file order matters to kotlinc the way statement order does inside a file kotlinc resolves the whole set of files as one program, not top-to-bottom like a script List files (or point at a directory) in whatever order is convenient -- it compiles the same either way
Reaching for Gradle the moment a project has two files Part 11's Gradle setup exists for dependency resolution and multi-module builds, not for "more than one file" Plain kotlinc on a directory handles multi-file projects fine; reach for Gradle only once a real dependency is needed
Writing "Kotlin 2.x added X" from memory Changelogs are easy to misremember, and flags/behavior can shift between minor releases Run kotlinc -version, then actually compile and run the feature before claiming it works
Expecting a context parameter to be passed like a normal argument context(logger: Logger) fun f() is still called as f(), with no logger in the call Call it inside a scope that already has the right type in context, e.g. with(logger) { f() }
Using a plain String/Double where a value class was the point Loses the whole benefit: arguments of the same underlying type can still be swapped by accident Use the value class (ShipmentId, Kilograms) in every signature, not just at construction
Letting a value class's init block be optional Without require(...) in init, an invalid value class instance (e.g. negative money) is just as constructible as a bad Double would have been Put every invariant in init, so an invalid instance can never exist in the first place

Quick recap

  • kotlinc file.kt -include-runtime -d app.jar packages a standalone, runnable jar; java -jar app.jar runs it anywhere a JVM exists; the manifest's Main-Class is set for you.
  • Multi-file Kotlin projects work with plain kotlinc pointed at a directory, in any file order -- no build tool needed until a real dependency or multi-module build shows up, which is exactly what Part 11's Gradle setup is for.
  • entries, data object, guard conditions in when, multi-dollar string templates, and context parameters are all real, working features on the installed kotlinc 2.4.21 -- checked here, not assumed from a changelog.
  • @JvmInline value class gives compile-time type safety for a single wrapped value, usually with no runtime cost -- confirmed with the same javap/reflection techniques as Part 15.
  • The splitbill mini-build packages a multi-file, value-class-based CLI into one runnable jar, tying every section of this part together.

Checklist

  • I packaged a one-file CLI as a runnable jar with -include-runtime and ran it with java -jar.
  • I reproduced the NoClassDefFoundError from leaving off -include-runtime, and fixed it by putting kotlin-stdlib.jar on the classpath.
  • I compiled a multi-file project by pointing kotlinc at a directory, and separately by listing the files in a different order, and got the same result both times.
  • I can explain, in my own words, the line between "plain kotlinc is enough" and "this needs Part 11's Gradle setup."
  • I compiled and ran every feature in section 3 myself, on this machine's kotlinc.
  • I wrote a value class with a validating init block, and triggered its rejection.
  • I built and ran the splitbill CLI, including at least one invalid-input case.

Search the guide