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

Part 12 / Topic 1 of 7

The worked example: a legacy carrier, wrapped

This part's running example is examples/interop-project/: a Java class standing in for an old carrier-rates library with no idea Kotlin exists, and a Kotlin object meant to be called from Java, that uses the Java class internally.

interop-project/
├── LegacyCarrierRates.java   -- plain Java, no Kotlin dependency at all
├── PricingApi.kt             -- Kotlin, calls the Java class AND is called from Java
├── GstUtils.kt               -- Kotlin, @JvmName-renamed for a nicer Java-facing name
└── Main.java                 -- plain Java, calls the Kotlin code above

Dependency direction: Main.java → PricingApi.kt/GstUtils.kt → LegacyCarrierRates.java. There's no genuine two-way cycle between a single Java file and a single Kotlin file here — that's deliberately avoided; kotlinc can read .java source for type information while compiling .kt files, but it doesn't actually compile the .java file itself, and (verified below) relying on raw .java source instead of an already-compiled .class can silently break Kotlin's getter/setter-to-property conversion. The reliable recipe — and the one that's actually been run here — compiles in dependency order instead:

$ javac -cp annotations-13.0.jar -d out LegacyCarrierRates.java  # 1. plain Java, no Kotlin yet
$ kotlinc -cp out PricingApi.kt GstUtils.kt -d out            # 2. Kotlin, sees the compiled Java class
$ javac -cp "out:kotlin-stdlib.jar" -d out Main.java          # 3. Java, sees the compiled Kotlin classes
$ java -cp "out:kotlin-stdlib.jar" com.stepshala.carrier.Main # 4. run

annotations-13.0.jar (the JetBrains org.jetbrains.annotations artifact LegacyCarrierRates.java imports @Nullable/@NotNull from) ships inside kotlinc's own install, at <kotlinc install dir>/../libexec/lib/annotations-13.0.jar — it's on kotlinc's classpath automatically, but plain javac has no idea it exists, so step 1 needs it added by hand. Step 2 doesn't need it again: by the time kotlinc reads LegacyCarrierRates.class from out, the annotations are already baked into the .class file's bytecode. Real, pasted output:

Quote (Pune, 4kg): Rs 140.0
Express quote (Pune, 4kg, +20%): Rs 168.0
Quote (Nagpur, 2kg, unserviced city): Rs 100.0
Carrier: BlueDart Legacy (surge: false)
GST on Rs 100: Rs 118.0

This is exactly what a mixed-source-set Gradle module does under the hood (Part 11): Kotlin compiles first, with Java sources visible for type resolution; Java compiles second, with Kotlin's .class output on its classpath.

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

Search the guide