Junior
How can you integrate Kotlin code with Java code?
sobes.tech AI
Answer from AI
Seamless integration of Kotlin with Java thanks to JVM compatibility:
-
Using Kotlin from Java:
- Kotlin classes and functions are accessible in Java.
- Kotlin
getterandsetterproperties are automatically generated and accessible from Java. - Kotlin
top-level functionscompile into static methods of a class named after the file + "Kt" (by default). @JvmStaticannotation for static methods incompanion object.@JvmOverloadsto generate overloaded methods for functions with default parameters.
// Java code calling Kotlin SomeKotlinClass kotlinObject = new SomeKotlinClass("hello"); System.out.println(kotlinObject.getProperty()); // Access property via getter KotlinFileKt.someTopLevelFunction(); // Call top-level function -
Using Java from Kotlin:
- Java classes and interfaces are directly accessible.
- Kotlin lambdas can be used instead of SAM conversions in Java 8+.
- Nullability of Java types is handled as "platform types" in Kotlin, requiring explicit null checks.
// Kotlin code calling Java import java.util.ArrayList fun useJavaClass() { val javaList = ArrayList<String>() // Using Java class javaList.add("item") val javaString: String? = javaMethodReturningNullable() // Platform type if (javaString != null) { println(javaString.length) // Null check required } } -
Interaction within a project:
- Kotlin and Java files can coexist in the same project and call each other.
- IDEs (e.g., IntelliJ IDEA) provide convenient navigation and refactoring between languages.
-
Build tools:
- Gradle and Maven support mixed Kotlin/Java projects.
-
Joint usage:
- You can start with Kotlin, gradually rewriting parts of Java code.
- You can start with a small amount of Kotlin code in an existing Java project.