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

Part 16 / Topic 5 of 5

Mini-build: your own packaged, runnable CLI tool

splitbill ties every section together: a multi-file project (section 2) under one package, using a value class for money (section 4) and a when with a guard condition (section 3), packaged as one runnable jar (section 1).

examples/05_mini_build_splitbill/
└── src/main/kotlin/com/stepshala/splitbill/
    ├── Money.kt     -- RupeesPaise (value class), applyGst
    ├── Command.kt   -- sealed Command, parse(args), run(command)
    └── Main.kt      -- fun main(args)

Command.kt's run function is the guard-condition example from section 3 doing real work -- splitting a bill one way for a solo "order" and another way for an actual group:

fun run(command: Command): String = when (command) {
    is Command.Split if command.people == 1 -> "Nothing to split, one person pays ${command.amount}"
    is Command.Split -> {
        val share = command.amount / command.people
        "Split ${command.amount} between ${command.people} people: $share each"
    }
    is Command.Gst -> "With 18% GST: ${applyGst(command.amount)}"
    is Command.Invalid -> "Error: ${command.reason}"
    Command.Help -> """
        |splitbill - a tiny Kotlin CLI, packaged with kotlinc
        |
        |usage:
        |  splitbill split <amountInr> <people>   split a bill evenly
        |  splitbill gst <amountInr>               add 18% GST
        |  splitbill help                          show this message
    """.trimMargin()
}

Packaged and run exactly like section 1, just with a package-qualified entry point:

$ kotlinc src/main/kotlin -include-runtime -d splitbill.jar
$ java -jar splitbill.jar split 900 4
Split Rs.900.00 between 4 people: Rs.225.00 each
$ java -jar splitbill.jar split 500 1
Nothing to split, one person pays Rs.500.00
$ java -jar splitbill.jar gst 1000
With 18% GST: Rs.1180.00
$ java -jar splitbill.jar split 900 0
Error: people must be at least 1, got 0
$ java -jar splitbill.jar split abc 4
Error: not a number: abc
$ java -jar splitbill.jar foo
Error: unknown command: foo
$ unzip -p splitbill.jar META-INF/MANIFEST.MF | grep Main-Class
Main-Class: com.stepshala.splitbill.MainKt

RupeesPaise's init { require(paise >= 0) { ... } } (section 4's pattern) is what makes RupeesPaise(-500) impossible to construct at all, so Command.Split/Command.Gst never need to re-check for a negative amount themselves -- the invalid state simply can't be built once parsing is past RupeesPaise.fromRupees(amount).

Full program: examples/05_mini_build_splitbill/.

Done here? The practice set for Part 16 — including the solutions — is on the part page.

Search the guide