0
0
Kotlinprogramming~5 mins

Collections interop behavior in Kotlin

Choose your learning style9 modes available
Introduction

Collections interop behavior helps Kotlin work smoothly with Java collections. It makes using lists, sets, and maps from Java easy and safe in Kotlin.

When you use Java libraries that return collections in your Kotlin code.
When you want to pass Kotlin collections to Java methods.
When you need to convert between Kotlin and Java collection types.
When you want to avoid copying collections for better performance.
When you want to use Kotlin collection functions on Java collections.
Syntax
Kotlin
val kotlinList: List<String> = javaList
val javaList: java.util.List<String> = kotlinList

Kotlin collections are interfaces that can wrap Java collections without copying.

You can use Kotlin collection functions on Java collections directly.

Examples
Java list is assigned to Kotlin list. Kotlin can read Java collections easily.
Kotlin
val javaList: java.util.List<String> = java.util.ArrayList()
javaList.add("apple")

val kotlinList: List<String> = javaList
println(kotlinList[0])
Kotlin mutable list can be used as Java list without copying.
Kotlin
val kotlinMutableList: MutableList<String> = mutableListOf("cat", "dog")

val javaList: java.util.List<String> = kotlinMutableList
println(javaList[1])
Java map can be used as Kotlin map directly.
Kotlin
val javaMap: java.util.Map<String, Int> = java.util.HashMap()
javaMap["one"] = 1

val kotlinMap: Map<String, Int> = javaMap
println(kotlinMap["one"])
Sample Program

This program shows how Kotlin and Java collections can be used interchangeably without copying. Changes in Kotlin mutable list reflect in Java list.

Kotlin
fun main() {
    val javaList: java.util.List<String> = java.util.ArrayList()
    javaList.add("Kotlin")
    javaList.add("Java")

    // Use Java list as Kotlin list
    val kotlinList: List<String> = javaList
    println("First element from Kotlin list: ${kotlinList[0]}")

    // Use Kotlin mutable list as Java list
    val kotlinMutableList: MutableList<String> = mutableListOf("Apple", "Banana")
    val javaListFromKotlin: java.util.List<String> = kotlinMutableList
    println("Second element from Java list: ${javaListFromKotlin[1]}")

    // Modify Kotlin mutable list and see change in Java list
    kotlinMutableList.add("Cherry")
    println("Java list size after Kotlin list modification: ${javaListFromKotlin.size}")
}
OutputSuccess
Important Notes

Kotlin collections wrap Java collections, so no extra memory is used.

Mutable collections in Kotlin correspond to Java collections that can be modified.

Be careful when modifying collections shared between Kotlin and Java to avoid unexpected changes.

Summary

Kotlin collections can wrap Java collections directly without copying.

This makes Kotlin and Java collections work smoothly together.

Mutable collections in Kotlin correspond to modifiable Java collections.