Can you list the main data structures used in Kotlin and describe them?
sobes.tech AI
Answer from AI
In Kotlin, the main data structures are represented as collections and arrays. Here are the main ones:
-
List — an ordered set of elements. It can be mutable (
MutableList) or immutable (List). It allows duplicates and access by index. -
Set — a collection of unique elements without a specific order. It can also be mutable (
MutableSet) or immutable (Set). -
Map — a collection of key-value pairs. Keys are unique. There are mutable (
MutableMap) and immutable (Map) options. -
Array — a fixed-size array of elements of the same type. In Kotlin, arrays are represented by the class
Array<T>. -
Sequence — lazy collections that are computed as needed, useful for large or infinite data streams.
Example usage:
val list: List<Int> = listOf(1, 2, 3)
val mutableList: MutableList<String> = mutableListOf("a", "b")
val set: Set<Int> = setOf(1, 2, 2, 3) // contains 1, 2, 3
val map: Map<String, Int> = mapOf("one" to 1, "two" to 2)
val array: Array<Int> = arrayOf(1, 2, 3)
// Sequence example
val seq = sequenceOf(1, 2, 3).map { it * 2 }
for (num in seq) {
println(num)
}
These data structures cover most tasks related to storing and processing collections in Kotlin.