Part 12 / Topic 6 of 7
Calling Kotlin from Java
Main.java calls everything from section 5 the way a real Java caller would — plain static
calls, no INSTANCE, no extra Kotlin-only ceremony:
double quote = PricingApi.quoteInr("Pune", 4.0);
double expressQuote = PricingApi.quoteInr("Pune", 4.0, 20.0);
System.out.println(PricingApi.carrierLabel());
System.out.println(GstUtils.withGst(100.0));
A Kotlin data class called from Java is worth seeing too — Coupon.getCode(),
.equals(), and friends are all real, generated methods, not Kotlin-only magic:
data class Shipment(val id: String, val weightKg: Double)
$ javap -p out/com/stepshala/carrier/Shipment.class
public final class com.stepshala.carrier.Shipment {
public final java.lang.String getId(); // val -> a getter, called shipment.getId() from Java
public final java.lang.String component1(); // destructuring support
public final com.stepshala.carrier.Shipment copy(java.lang.String, double);
public java.lang.String toString();
public int hashCode();
public boolean equals(java.lang.Object);
...
}
Every one of those is a plain, callable Java method — shipment.getId(), shipment.toString(),
shipment.equals(other) — Java code never needs to know Shipment was written in Kotlin.
Full files: examples/interop-project/Main.java, ShipmentData.kt.
Done here? The practice set for Part 12 — including the solutions — is on the part page.