Sobes.tech
Junior

What types of collections does Kotlin support?

sobes.tech AI

Answer from AI

Kotlin supports the standard collection types from the Java Collection Framework, as well as provides its own convenient extensions and interfaces.

Main collection interfaces in Kotlin:

  • Collection<out E>: Basic interface for an immutable collection.
  • MutableCollection<E>: Interface for a mutable collection.
  • List<out E>: Interface for an immutable ordered collection accessible by index.
  • MutableList<E>: Interface for a mutable ordered collection accessible by index.
  • Set<out E>: Interface for an immutable collection of unique elements without a specific order.
  • MutableSet<E>: Interface for a mutable collection of unique elements without a specific order.
  • Map<K, out V>: Interface for an immutable collection of key-value pairs.
  • MutableMap<K, V>: Interface for a mutable collection of key-value pairs.

Main implementations of collections in Kotlin's standard library (often used are builder functions):

  • ArrayList: A mutable list based on an array.
  • LinkedList: A mutable list based on a linked list.
  • HashSet: A mutable set based on a hash table.
  • LinkedHashSet: A mutable set based on a hash table and linked list (preserves insertion order).
  • HashMap: A mutable map based on a hash table.
  • LinkedHashMap: A mutable map based on a hash table and linked list (preserves insertion order).

Examples of creating collections:

// Immutable list
val immutableList = listOf("a", "b", "c")

// Mutable list
val mutableList = mutableListOf(1, 2, 3)

// Immutable set
val immutableSet = setOf("apple", "banana")

// Mutable set
val mutableSet = mutableSetOf(10, 20, 30)

// Immutable map
val immutableMap = mapOf("key1" to "value1", "key2" to "value2")

// Mutable map
val mutableMap = mutableMapOf("a" to 1, "b" to 2)

The key difference between mutable (Mutable*) and immutable (*) versions is that mutable collections provide methods for adding, removing, and modifying elements, while immutable collections do not. Builder functions listOf, setOf, mapOf create immutable collections, and mutableListOf, mutableSetOf, mutableMapOf create mutable ones.

Advantages of using Kotlin collections:

  • Safety: Immutable collections by default help prevent unintended modifications.
  • Extensions: Kotlin provides many useful extension functions for working with collections (filter, map, forEach, etc.).
  • Interoperability: Easy to work with existing Java code using collections from the Java Collection Framework.
What types of collections does Kotlin support? — Kotlin - sobes.tech