Skip to content
Tutorials Center
My learning

Topics

Lesson 110 of 134 ยท Testing and Tooling

Java Interoperability

Learn Kotlin and Java interoperability: calling Java from Kotlin, platform types and nullability, SAM conversion, mapped types, and @JvmStatic, @JvmField, @JvmOverloads, @Throws.

Kotlin was designed to live next to Java. It compiles to the same bytecode, runs on the same JVM and can call any Java library without wrappers or glue code: the JDK, Spring, Jackson, JDBC drivers, millions of packages on Maven Central. The other direction works too, so a Java project can adopt Kotlin one file at a time. This is the biggest practical reason Kotlin grew so fast: you never have to rewrite anything.

Interoperability is mostly invisible, until it is not. A few corners behave differently from what a Kotlin-only world suggests: nullability that Java does not state, collections with two names, generated getters and static members that Kotlin models differently. This lesson walks through both directions and shows what the compiler really produces. On this site everything runs on JDK 25, so every JDK example below is real. Java source files cannot be compiled by the runner, so Java code appears as read-only snippets. See also Null Safety and Annotations.

Calling Java from Kotlin

Any Java class is usable by importing it. Kotlin reads Java getters and setters as properties, lets you drop new and treats Java's static methods like top-level functions of the class:

Kotlin Using the JDK from Kotlin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice thread.name = "worker". Java's setName(String) and getName() pair up as a Kotlin property because they follow the getter/setter naming convention. Kotlin does this for every Java class, so file.name, thread.isDaemon and list.size all read naturally.

Two Kotlin keywords collide with Java names. If a Java method is called in or is, put backticks around it: System.`in` . This is the reason the runner's standard input is System.in``.

Platform types: Java does not say "nullable"

Here is the most important interop idea. Kotlin separates String from String?, but Java has only String, and any Java reference might be null. When Kotlin calls Java code that carries no nullability information, it cannot know. It uses a special platform type, written String! in error messages and IDE hints. A platform type means "I do not know; you decide". You may treat it as String or as String?, and the compiler checks neither.

Kotlin A platform type hides a null (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first two prints work: null and null. The last line compiles because risky is a platform type, and it fails at run time with Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "risky" is null. The null got inside your Kotlin code without the compiler noticing.

The defence is simple: decide the type yourself at the boundary. Write val value: String? = javaCall() whenever the Java method might return null, and val value: String = javaCall() only when its documentation promises non-null (Kotlin then inserts a check at that line, so a surprise null fails there, not ten calls later). Never leave the type inferred for values that come from Java and might be null.

Java code can help the compiler. Kotlin understands nullability annotations from JetBrains, Android, Spring, JSpecify and several other libraries: a Java method annotated @Nullable String find(...) shows up in Kotlin as String?, and @NotNull as String. Well-annotated libraries (such as Spring) give you real null safety across the language border.

Mapped types: one list, two names

Kotlin does not have its own List implementation. The Kotlin types List, MutableList, Map, Set, String, Int and others are mapped to Java classes at compile time. Both views are the same object at run time, which is why no conversion is needed when you pass collections to Java:

Kotlin Kotlin types and their Java classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Some consequences worth remembering:

  • A Java method taking java.util.List<String> accepts a Kotlin List<String> or MutableList<String>. Kotlin's read-only List is only a view: Java code can still modify the same object. Do not pass a Kotlin listOf(...) to Java code you do not trust.
  • Int is a primitive int where possible (locals, parameters, IntArray) and a boxed java.lang.Integer where it has to be an object (Int?, List<Int>, generics). Boxing in a hot loop costs speed, which is why IntArray exists.
  • Java's Object is Kotlin's Any, Java's void is Unit, and a Java varargs parameter becomes a Kotlin vararg (use *array to spread).

SAM conversion: lambdas for Java interfaces

Many Java APIs expect an object of an interface with a single abstract method (a SAM interface): Runnable, Comparator, Callable, Function, Predicate. Kotlin lets you write a lambda wherever such an interface is expected:

Kotlin Lambdas as Java interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

When the target type is not obvious from the call (for example when you assign to a val), name the interface in front of the braces: Runnable { ... }. The same trick works for your own Kotlin interfaces if you declare them with fun interface (see Interfaces).

Calling Kotlin from Java

When Java calls Kotlin, it sees what the compiler generated. Knowing the translation rules lets you design Kotlin code that is pleasant to use from Java. The key rules, as read-only Java:

Java
// read-only example: Java code calling the Kotlin class below
Settings s = new Settings();
s.setName("demo");                         // var name   -> getName() / setName()
boolean ok = s.isReady();                  // val isReady -> isReady() (name kept)
String greeting = s.greet("hi", 3);        // normal member function
Settings.Companion.plain();                // companion member: via the Companion object
Settings.create();                         // @JvmStatic: a real static method
int d = Settings.DEFAULT;                  // @JvmField: a public static field
String all = SettingsKt.shout("x");        // top-level function in Settings.kt

And the Kotlin that produced it:

Kotlin
// read-only example (Settings.kt)
class Settings {
    companion object {
        @JvmStatic fun create() = Settings()
        fun plain() = Settings()
        @JvmField val DEFAULT = 5
        const val MAX = 10
    }
    var name: String = "x"
    val isReady: Boolean = true
    @JvmOverloads fun greet(prefix: String = "a", count: Int = 1) = prefix.repeat(count)
    @Throws(java.io.IOException::class) fun load() { /* ... */ }
}

fun shout(text: String) = text.uppercase()

You do not need to take this on trust: the next example is a self-contained Kotlin file that asks Java reflection what the compiler generated for a similar class (see Reflection Overview).

Kotlin What the compiler generates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output tells the story. getName and setName come from the var. The Boolean isReady keeps its name. @JvmOverloads produced three greet methods, because Java has no default arguments (a fourth greet$default helper is what Kotlin callers use). @JvmStatic made create a real static method on Settings, while plain stays inside the Companion object. @JvmField and const val become static fields. And without @Throws, Java would not be allowed to catch IOException from load, since Java's checked exceptions are enforced by the Java compiler, not by the JVM.

The annotations at a glance

Annotation Effect for Java callers
@JvmStatic Companion/object member becomes a static method
@JvmField Property becomes a public field, with no getter/setter
@JvmOverloads One overload per default argument
@Throws(X::class) Declares a checked exception
@JvmName("x") Renames the JVM method (also for getters with @get:JvmName, and files with @file:JvmName)
@JvmRecord A data class compiled as a Java record

Things that do not translate

A few Kotlin features have no Java equivalent, so Java sees awkward shapes:

  • Extension functions become static methods with the receiver as the first parameter (StringsKt.shout(text)).
  • Default arguments need @JvmOverloads, as above.
  • Inline functions with reified type parameters cannot be called from Java at all.
  • Suspend functions get an extra Continuation parameter. Calling them from Java is painful; expose a CompletableFuture wrapper (from kotlinx-coroutines-jdk8) instead.
  • Value classes are unboxed, so the JVM signature contains the underlying type and a mangled name.
  • Properties have no Java counterpart; Java sees methods. Use @JvmField or const only where you really want fields.

When you write a library used by both languages, design the public API with these in mind, and keep the surprising parts internal.

A pragmatic migration path

Because interop is two-way, a Java codebase can migrate gradually. A good order is: add Kotlin to the build; write new code and tests in Kotlin; convert small leaf classes (data holders, utilities) next; leave the framework-heavy core for last. Add nullability annotations to the Java code you keep, so the Kotlin side sees String? instead of String!. The IDE's "Convert Java File to Kotlin" is a good start but always needs a human pass: check platform types it left behind and replace !! with real null handling. For the language-level differences read Kotlin for Java Developers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of a value returned by a Java method that has no nullability annotation?

    Platform types mean 'unknown nullability'. You can use them as T or T?, but a wrong guess fails at run time with a NullPointerException.
  2. 2. Which line is the safest way to receive a possibly-null Java result?

    Declaring the nullable type yourself forces the compiler to make you handle null. Plain inference keeps the platform type and checks nothing.
  3. 3. How does Java code call a Kotlin companion function that has no annotations?

    Companion members live in a nested Companion object. Add @JvmStatic to get a real static method on the outer class.
  4. 4. What does @JvmOverloads do?

    Java has no default arguments, so the annotation generates a method for each shorter parameter list.
  5. 5. Why can a Kotlin List<Int> be passed to Java without conversion?

    Mapped types are the same class at run time. This also means Java may modify a Kotlin read-only list, since read-only is only a compile-time view.

Summary

  • Kotlin calls any Java code directly; getters and setters read as properties and static members are used through the class name.
  • Values from unannotated Java code have platform types: declare T? yourself where null is possible.
  • Kotlin's List, Map, String and Int are mapped to Java types, so no conversions are needed; read-only is only a Kotlin-side promise.
  • SAM conversion lets you pass lambdas for Runnable, Comparator, Callable and similar Java interfaces.
  • Use @JvmStatic, @JvmField, @JvmOverloads, @JvmName and @Throws to give Java callers a natural API; extension functions, reified inline functions and suspend functions are awkward from Java.
  • Migrate Java projects gradually: tests and new code first, annotate the Java you keep with nullability.

Next: Kotlin on Android