Skip to the content.

Collections

Kotlin offers view interfaces over the standard Java collections in the 🔗 kotlin.collections package

Pair

val pair1 = Pair("Alice", "Bob")
val pair2 = "Alice" to "Bob" // infix for "Alice".to("Bob")

Array

Construct using the 🔗 arrayOf() function.

val arr1 = arrayOf("Alice", "Bob", "Eve")
val arr2 = Array(3) { i -> i * 2 } // construct an array of size 3 with an initialization function
println(arr2.joinToString()) // 0, 2, 4
println(arr2::class) // class kotlin.Array
println(arr2.javaClass) // class [Ljava.lang.Integer;

For arrays of native types (non-boxed) use the specific functions like intArrayOf()

List

Construct using the 🔗 listOf() function for an immutable list. Use 🔗 mutableListOf() for a mutable list.

val strList = listOf("Alice", "Bob", "Eve") // type List<String>
println(strList::class) // class java.util.Arrays$ArrayList
println(strList.javaClass) // class java.util.Arrays$ArrayList

As seen the kotlin.collections.List is a compile-time view around the immutable java.util.Arrays#ArrayList

Since it is immutable the plus/+ and minus/- operations should be used to return a copy of the list.

val list = listOf("Alice", "Bob")
val copy1 = list + "Eve" // list is immutable, returns a new copy [Alice, Bob, Eve]
val copy2 = copy1 - "Bob" // [Alice, Eve]

Set

Construct using the 🔗 setOf() function for an immutable set. Use 🔗 mutableSetOf() for a mutable set.

If a specific Set type is needed use one of the following

Map

Construct using the 🔗 mapOf() function for an immutable map. Use 🔗 mutableMapOf() for a mutable map.

If a specific Map type is needed use one of the following

val map = mapOf("Alice" to "Bob", "Eve" to "Boris") // varargs of Pairs
println(map.containsKey("Alice")) // true
println(map.contains("Alice")) // true
println("Alice" in map) // true
println(map.containsValue("Bob")) // true

// alicesPartner should be a nullable type - `String?`
val alicesPartner: String = map.get("Alice") // error: type mismatch: inferred type is String? but String was expected
val alicesPartner = map["Alice"] // type is `String?`

Operations to get a copy of an immutable map with elements added/removed

val copy1 = map + ("Doris" to "Hans") // {Alice=Bob, Eve=Boris, Doris=Hans}
val copy2 = copy1 - "Eve" // {Alice=Bob, Doris=Hans}

Iteration

for (entry in map) {
  println("${entry.key} = ${entry.value}")
}

// with destructuring of the data entry type
for ((key, value) in map) {
  println("$key = $value")
}