Question #378MediumNative Android

How does Kotlin handle Java interoperability?

#kotlin#java#interoperability

Answer

Overview

Kotlin is 100% interoperable with Java. You can call Java from Kotlin and vice versa.


Calling Java from Kotlin

kotlin
// Call Java classes directly
val list = ArrayList<String>()
list.add("Kotlin")

// Use Java libraries
val file = File("/path/to/file")
val reader = BufferedReader(FileReader(file))

Calling Kotlin from Java

Kotlin Code

kotlin
class User(val name: String) {
    fun greet() = "Hello, $name"
}

object Constants {
    const val API_KEY = "123"
    
    @JvmStatic
    fun getBaseUrl() = "https://api.example.com"
}

Java Code

java
User user = new User("Alice");
String greeting = user.greet();

String apiKey = Constants.API_KEY;
String url = Constants.getBaseUrl();

@JvmStatic

kotlin
class Utils {
    companion object {
        @JvmStatic
        fun square(x: Int) = x * x
    }
}
java
// Java can call as static method
int result = Utils.square(5);

@JvmField

kotlin
class Config {
    @JvmField
    val timeout = 30
}
java
int t = new Config().timeout; // Direct field access

@JvmOverloads

kotlin
fun greet(name: String, greeting: String = "Hello") {
    println("$greeting, $name")
}

Without

text
@JvmOverloads
, Java must provide all parameters.

kotlin
@JvmOverloads
fun greet(name: String, greeting: String = "Hello") { }
java
greet("Alice"); // Works now
greet("Bob", "Hi");

Null Safety Bridge

kotlin
// Kotlin sees Java types as platform types
val str: String = javaMethod() // May crash if null
val str: String? = javaMethod() // Safe

File Names

Kotlin file

text
Utils.kt
with top-level functions:

kotlin
fun square(x: Int) = x * x

Java sees it as:

java
UtilsKt.square(5);

Customize with

text
@file:JvmName
:

kotlin
@file:JvmName("MathUtils")
package com.example

fun square(x: Int) = x * x
java
MathUtils.square(5);

Key Point: Seamless interop allows gradual migration from Java to Kotlin.