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 astotal. A boolean getter likeisPaid()becomesisPaid. - 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 asString!. 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.