Part 16 / Topic 2 of 5
Multi-file project layout without Gradle
A real CLI usually outgrows one file. kotlinc doesn't need a build tool to compile several
files that reference each other -- it reads all of them, resolves every cross-file reference
itself, and the standard project shape (src/main/kotlin/<package>/...) works perfectly well
with no build.gradle.kts in sight:
examples/02_multi_file_billcalc/
└── src/main/kotlin/com/stepshala/billcalc/
├── Pricing.kt -- fun applyGst(...)
└── Main.kt -- fun main(args), calls applyGst
Compile it either by listing the files, in any order:
$ kotlinc src/main/kotlin/com/stepshala/billcalc/Main.kt src/main/kotlin/com/stepshala/billcalc/Pricing.kt -include-runtime -d billcalc.jar
...or by pointing kotlinc at the whole source directory, which is what every example in this
part actually uses:
$ kotlinc src/main/kotlin -include-runtime -d billcalc.jar
$ java -jar billcalc.jar 1500 5
Rs.1500.00 + 5% GST = Rs.1575.00
$ unzip -p billcalc.jar META-INF/MANIFEST.MF | grep Main-Class
Main-Class: com.stepshala.billcalc.MainKt
Both compile cleanly and run identically -- Main.kt listed before Pricing.kt works exactly
the same as the other way around, because kotlinc type-checks the whole set of files together
before generating any bytecode, the same way it would for one big file. The package declaration
(package com.stepshala.billcalc) is what makes Main-Class come out as
com.stepshala.billcalc.MainKt instead of a bare MainKt.
Where this stops scaling, and what Part 11 buys you
This works right up until a project needs something kotlinc genuinely can't do on its own:
fetch a dependency from Maven Central (a test framework, a JSON library, coroutines), or build
more than one module against each other. Part 11
is exactly that moment -- it introduces the standard src/main/kotlin / src/test/kotlin
layout this part reuses, plus Gradle and the Kotlin DSL (build.gradle.kts) for dependency
resolution, running tests, and everything else a loose kotlinc invocation was never meant to
do. This part stays deliberately on the other side of that line, on purpose: it's the honest
boundary of what "no build tool" can and can't do, not a reason to avoid Gradle once a project
needs it.
Full program: examples/02_multi_file_billcalc/.
Done here? The practice set for Part 16 — including the solutions — is on the part page.