Java Interoperability
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.
The shortcut
When reading mixed code, translate at the border with two questions: "Is this a getter or setter?" (then it is a property) and "Did this value come from Java?" (then its nullability is unknown until you decide).
The Java side
CustomerhasgetName()returningStringandisMember()returningboolean.
The trap is declaring val name: String = customer.name and assuming it is safe. If Java hands back null, Kotlin throws at that exact line.
Drills
Answer fast — trust the rule.
Why can Kotlin call a Java class without any bridge code?
A Java class has getPrice() and setPrice(double). How does Kotlin usually read the price?
What does the type String! in a Kotlin error message mean?
A top-level function fun tax() lives in Prices.kt. What does Java call it?
Remember
- Kotlin and Java share bytecode, so each calls the other directly.
- Java getters and setters show up in Kotlin as properties.
- Values from Java have unknown nullability: decide, and check.
