0
0
Kotlinprogramming~5 mins

Why Java interop matters in Kotlin

Choose your learning style9 modes available
Introduction

Kotlin can work together with Java easily. This helps you use many Java tools and libraries without extra work.

You want to use a Java library in your Kotlin app.
You have an existing Java project and want to add Kotlin code.
You want to use Android APIs which are mostly in Java.
You want to mix Kotlin and Java code in the same project.
You want to gradually move from Java to Kotlin without rewriting everything.
Syntax
Kotlin
No special syntax needed. Kotlin code can call Java classes and methods directly, and Java code can call Kotlin classes with some rules.
Kotlin classes and functions are visible to Java if they are declared properly (e.g., public).
Some Kotlin features like properties and null safety have special ways to work with Java.
Examples
This Kotlin code uses Java's ArrayList class directly.
Kotlin
val list = java.util.ArrayList<String>()
list.add("Hello")
println(list[0])
Kotlin class and method can be called from Java code.
Kotlin
class KotlinClass {
    fun greet() = "Hi from Kotlin"
}

// Java can call KotlinClass.greet() like a normal method.
Sample Program

This program shows Kotlin using a Java class directly without extra setup.

Kotlin
fun main() {
    // Using Java's ArrayList in Kotlin
    val javaList = java.util.ArrayList<String>()
    javaList.add("Kotlin and Java")
    println(javaList[0])
}
OutputSuccess
Important Notes

Interop lets you reuse Java code, saving time and effort.

Be careful with null values when calling Java from Kotlin to avoid crashes.

Some Kotlin features like extension functions are not visible in Java.

Summary

Kotlin and Java can work together smoothly.

This helps use existing Java tools and code easily.

Interop makes moving from Java to Kotlin easier.