Instruction 1

Collections

A collection in Kotlin is a group of items. Think of situations as a programmer where you’d use collections. These collections could be items from the grocery store or letters of the alphabet. Collections could also be countries on a continent or members of a family. Visit Kotlin Playground to start a new session.

Here’s how you can initialize a collection in Kotlin with a list of items:

fun main() {
  val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
  println(oceans)
}

Run the code above, and it prints the contents of the collection:

[Pacific Ocean, Southern Ocean, Arctic Ocean, Atlantic Ocean, Indian Ocean]

There are three basic types of collections in Kotlin: List, Set, and Map. The first one you’ll learn about is List.

Using Lists

A List stores items in the order in which they’re added or created. This is a useful property to keep in mind. It’s not the same for every type of collection. You’ll see an ordering difference in the other types of collections.

In the previous example, you can see that the items printed in the same order in which they were initialized.

A List will also duplicate items. The following is a valid List:

[Pacific Ocean, Southern Ocean, Arctic Ocean, Atlantic Ocean, Indian Ocean, Indian Ocean, Indian Ocean]

The List doesn’t manage duplicate items. You’ll see later that other collection types manage and remove duplicates.

Indexing

You access the elements using a zero-based index. This means that the first item in the list has an index of 0. This is an important property of collections. In Kotlin, as well as most other programming languages, counting begins at 0 instead of 1.

Note: Why is 0-based element numbering used with a List? When you ask for an element, you’re telling the computer how many elements to count to get to your desired element. If you start at the beginning element of the List, how many elements do you move to get to the beginning element? The answer is 0: you’re on the beginning element. This will become more familiar as you use the List collection.

Using the previous example, print out the first item in the console using the following snippet:

fun main() {
  val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
  println(oceans[0]) // Prints "Pacific Ocean"
}

Run the program. The output follows:

[Pacific Ocean]

It prints “Pacific Ocean” since it’s the first item in the list. If you want the second item, you increment the index by 1 until you get to the end of the list.

Note: The list’s contents in the displayed output are in square braces, [].

For lists, you access a particular position by putting its index in square brackets, as shown above.

Implementing Mutable Lists

Now that you’re able to reference items in a List at specific positions, what can you do with these elements? You can remove the element if the collection is mutable - editable or changeable.

Collections in Kotlin may either be mutable or immutable. An immutable collection has a fixed size - you can’t add any more items, nor can any elements be removed. Mutable collections are represented by the List interface.

Unlike an immutable list, a mutable list has a variable size. Items can be added and removed. The previous example shows how to initialize an immutable list. To create a mutable list, use mutableListOf instead. Mutable lists are represented by the MutableList class:

fun main() {
  val oceans = mutableListOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
  println(oceans)
}

To add items to a mutable list, you can use the add method:

fun main() {
  val oceans = mutableListOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean")
  println(oceans)
  oceans.add("Indian Ocean")
  println(oceans)
}

For mutable collections, you can also remove items. Remove the item at the third index. Remember 0-based numbering? To remove the third element, Arctic Ocean, reference it as element 2 below. For instance, use removeAt():

fun main() {
  val oceans = mutableListOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean")
  oceans.removeAt(2)
  println(oceans)
}

Run the above code. oceans now contain only 2 items:

[Pacific Ocean, Southern Ocean]

Immutable Lists

Immutable collections may be assigned to a mutable or an immutable variable. A collection’s mutability is different from the mutability of the variable it’s assigned to. The immutability of a list applies to the elements in the collection and not the variable or object itself. So if an immutable collection is assigned a var, the variable or object can be updated in the course of the program. And if an immutable collection is assigned a val, it can’t be updated:

fun main() {
  var oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean")
  println(oceans)
  oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
  println(oceans)
}

This would result in an error if oceans was an immutable variable:

fun main() {
  val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean")
  println(oceans)
  oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
  println(oceans)
}

Run the above code. The output shows the following error:

Val cannot be reassigned

Also, since the list is immutable, the items in the collection can’t be updated. An immutable list has no add method like a mutable list.

fun main() {
  val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean")
  println(oceans)
  oceans.add("Indian Ocean") // Not possible
  println(oceans)
}

Run the above code, and the output shows the following error:

Unresolved reference: add

A mutable list can be assigned to an immutable variable and can then be modified. The variable doesn’t have to be mutable because the collection is mutable. From the above val example, make oceans immutable with mutableListOf(). You can now update its content:

fun main() {
  val oceans = mutableListOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean")
  println(oceans)
  oceans.add("Indian Ocean")
  println(oceans)
}

To know how many items are in a list, use the size() method like this:

fun main() {
  val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
  println(oceans)
  println("There are ${oceans.size} oceans in the world.")
}

A collection can contain many of the same items. Kotlin makes it possible to iterate over the entire contents and operate in the same way on each item. Here’s how to do it in Kotlin:

fun main() {
  val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
  for (ocean in oceans) {
      println(ocean)
  }
}

ocean, in this case, is an arbitrary variable that holds the item during each iteration. You can rename it to suit whatever works best in your situation.

Note: iterate means to repeat. In the above example, the iterator, for, repeats the same command. It performs println(ocean) for every item in the oceans list.

Comparing Lists

To compare two lists, use the equality operator ==. For two lists to be equal, they must have the same data type, content, number of items, and be in the same order.

fun main() {
  val oceans1 = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
  val oceans2 = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
  println(oceans1 == oceans2) // Prints true
}

The next type of collection is called Set.

See forum comments
Download course materials from Github
Previous: Introduction Next: Instruction 2