Skip to the workspace
Pebellslearn by building
Introduction to Kotlin  ›  Lesson

Java Interoperability

Java Interoperability 12 minKotlin and Java compile to the same JVM bytecode, so each can call the other directly, with Java getters appearing as Kotlin properties and Java's unknown nullability shown as platform types.

kotlin / Java Interoperability

Explore each scene at your own pace.

01 · The rule

The rule

Java Interoperability

Kotlin and Java compile to the same JVM bytecode, so each can call the other directly, with Java getters appearing as Kotlin properties and Java's unknown nullability shown as platform types.

Call Java code while checking nullability and other information the boundary may lose.

Pebble Café already has ten years of Java code: receipts, tax rules, a printer driver. Nobody wants to rewrite it. The good news is that a Kotlin file can sit in the same project and use those Java classes as if they were written in Kotlin.

The rule

Same bytecode, same JVM: Kotlin and Java call each other freely.

The Kotlin compiler produces .class files, exactly like the Java compiler does. The JVM cannot tell which language a class came from, so calls cross in both directions without any glue code.

Given this Java class:

public class Receipt {
    private double total;
    public double getTotal() { return total; }
    public void setTotal(double t) { total = t; }
}

Kotlin uses it like this:

val receipt = Receipt()      // no "new" keyword in Kotlin
receipt.total = 12.5         // calls setTotal(12.5)
println(receipt.total)       // calls getTotal()

Two small translations happen automatically:

  • Getters and setters become properties. getTotal() / setTotal() read as total. A boolean getter like isPaid() becomes isPaid.
  • Nullability becomes unknown. Java does not say whether a method can return null, so Kotlin gives the result a platform type, shown in error messages as String!. You may treat it as nullable or not, and the responsibility is yours.

Going the other way, Java can call Kotlin too. A top-level Kotlin function in Prices.kt appears to Java as a static method on a class named PricesKt. Annotations such as @JvmStatic and @JvmOverloads adjust how Kotlin code looks from the Java side.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.