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
kotlinclass User(val name: String) { fun greet() = "Hello, $name" } object Constants { const val API_KEY = "123" @JvmStatic fun getBaseUrl() = "https://api.example.com" }
Java Code
javaUser user = new User("Alice"); String greeting = user.greet(); String apiKey = Constants.API_KEY; String url = Constants.getBaseUrl();
@JvmStatic
kotlinclass Utils { companion object { @JvmStatic fun square(x: Int) = x * x } }
java// Java can call as static method int result = Utils.square(5);
@JvmField
kotlinclass Config { @JvmField val timeout = 30 }
javaint t = new Config().timeout; // Direct field access
@JvmOverloads
kotlinfun greet(name: String, greeting: String = "Hello") { println("$greeting, $name") }
Without
text
@JvmOverloadskotlin@JvmOverloads fun greet(name: String, greeting: String = "Hello") { }
javagreet("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.ktkotlinfun square(x: Int) = x * x
Java sees it as:
javaUtilsKt.square(5);
Customize with
text
@file:JvmNamekotlin@file:JvmName("MathUtils") package com.example fun square(x: Int) = x * x
javaMathUtils.square(5);
Key Point: Seamless interop allows gradual migration from Java to Kotlin.