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

Part 12 / Topic 2 of 7

Calling Java from Kotlin

LegacyCarrierRates.java has a constructor, a @Nullable-annotated method, an @NotNull method, an is-prefixed boolean getter/setter pair, an unannotated method, and a static method — five different things Kotlin treats five different ways:

public class LegacyCarrierRates {
    @Nullable
    public Double ratePerKgFor(String city) { ... }      // -> Double? in Kotlin

    public String operatorNote(String city) { ... }      // -> String! (a platform type -- section 3)

    @NotNull
    public String carrierName() { ... }                  // -> String (never null) in Kotlin

    public boolean isSurgeActive() { ... }                // -> property `isSurgeActive`
    public void setSurgeActive(boolean surgeActive) { ... }  // same property, now assignable

    public static double flatRateInr() { ... }            // -> LegacyCarrierRates.flatRateInr() in Kotlin
}
val legacy = LegacyCarrierRates()
val ratePerKg = legacy.ratePerKgFor(city) ?: LegacyCarrierRates.flatRateInr()  // Double? forces a check
val label = "${legacy.carrierName()} (surge: ${legacy.isSurgeActive})"        // property syntax, no ()

The getter/setter rule has a genuine surprise in it, caught while verifying this file for real: a boolean getter named isXxx() keeps its full name as a Kotlin property — isSurgeActive, not surgeActive. That's different from a plain getXxx()/setXxx() pair, which does drop the get/set prefix (getCount()/setCount() → the property count). Writing legacy.surgeActive here fails to compile with unresolved reference 'surgeActive' — the property genuinely keeps the is.

Full file: examples/interop-project/LegacyCarrierRates.java.

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

Search the guide