Skip to content
AgileLogics
5 min read

Java Interoperability

Prerequisites: Classes and objects, Null safety

Kotlin was designed to work seamlessly with Java. Kotlin code can use any Java library, Java code can call Kotlin, and both languages can live in the same project — which is how many teams migrate gradually.

Using Java from Kotlin

Java classes are used like Kotlin classes. Java getters and setters appear as properties:

import java.time.LocalDate
import java.util.UUID

fun main() {
    val date = LocalDate.of(2025, 3, 14)
    println(date.year)            // Java: date.getYear()
    println(date.month)           // Java: date.getMonth()

    val id = UUID.fromString("123e4567-e89b-12d3-a456-426614174000")
    println(id.version())

    val builder = StringBuilder()
    builder.append("Kotlin").append(" + ").append("Java")
    println(builder)
}
2025
MARCH
1
Kotlin + Java

Platform types: Java doesn't know about nullability

Java doesn't mark which values can be null, so Kotlin can't be sure. A value coming from Java has a platform type (shown as String! in IntelliJ) — Kotlin lets you treat it as nullable or non-null, and it's up to you to be right.

fun main() {
    val home: String? = System.getenv("SOME_UNSET_VARIABLE")   // safe
    println(home ?: "not set")
}
not set

Declaring the Java value as nullable (String?) is the safe choice when you aren't sure. Many Java libraries now add @Nullable / @NotNull annotations, which Kotlin reads and enforces.

Using Kotlin from Java

A few annotations make Kotlin code friendlier to Java callers:

object MathUtils {
    @JvmStatic
    fun square(n: Int) = n * n     // Java can call MathUtils.square(4)
}

class Greeter @JvmOverloads constructor(
    val name: String,
    val greeting: String = "Hello",  // Java gets both constructor versions
)
  • @JvmStatic — call object or companion members without .INSTANCE or .Companion.
  • @JvmOverloads — generate Java overloads for default arguments, which Java doesn't support.
  • Top-level functions in Utils.kt become static methods of a class named UtilsKt; @file:JvmName("Utils") renames it.

Migrating from Java

IntelliJ can convert a Java file to Kotlin (Code → Convert Java File to Kotlin File). The result compiles but usually needs tidying — for example, replacing !! with proper null handling and Java-style loops with collection functions.