Kotlin Collections

Just as Java has a collections framework, Kotlin also has a collections framework. Kotlin’s collections framework includes read-only (immutable) collections and mutable (read/write) collections.

Collection & MutableCollection

This is the kotlin.collection.Collection interface.

interface Collection<out E> : Iterable<E>

E is the element type of the Collection. This interface supports read-only access.

Read/write operations are supported by the MutableCollection interface.

interface MutableCollection<E> : Collection<E>, MutableIterable<E>

E is the element type of Collection.

List & MutableList

The List interface inherits from the Collection interface.

interface List<out E> : Collection<E>

E is the element type of Collection. This interface supports read-only access to a List.

Reading and writing are supported by the MutableList interface.

interface MutableList<E> : List<E>, MutableCollection<E>

E is the element type of the collection. This interface provides functions for adding and removing elements.

Creating Arrays and Lists

Arrays are created by instantiating the Array class. Create an array in the following form.

Array<TypeName>(element count) { initialization logic }

List<TypeName>(element count) { initialization logic }

Let’s look at a simple implementation example.

fun main() {
    val evenNumbers = Array(10) { it * 2 }

    for (n in evenNumbers) {
        println(n)
    }
}

Output:

0
2
4
6
8
10
12
14
16
18

The example above declares even numbers.

Creation Standard Library

For declaring arrays and lists, Kotlin’s standard library provides functions such as arrayOf, listOf, arrayListOf, and linkedListOf.

  • arrayOf
    • Conveniently creates an Array instance.
  • listOf:
    • Creates a java.util.List.
    • Its elements cannot be changed.
  • arrayListOf
    • Creates a java.util.ArrayList instance.
    • As in Java, adding and removing elements is possible.
  • linkedListOf
    • Creates a java.util.LinkedList instance.
    • As in Java, adding and removing elements is possible.
val oddNumbers = arrayOf(1, 3, 5, 7, 9)
val list = listOf(1,2,3,4,5)
val arrayList = arrayListOf(1,2,3,4,5)
val linkedList = linkedListOf(1,2,3,4,5)

References