You already have a basic idea of collections, their different types (set, list, map), and variations (mutable, immutable). In this topic, we will take a closer look at one specific type,
List
.Introduction
List is an immutable collection. Its size cannot be changed after it is initialized. This type allows duplicates and stores elements in a specific order.
Let's assume we want to save information about the cars we drove last year. Let's do it with the help of List:
val cars = listOf<String>("BMW", "Honda", "Mercedes")
println(cars) // output: [BMW, Honda, Mercedes]
Theoretically, we could use a MutableList to hold this kind of information:
val cars = mutableListOf<String>("BMW", "Honda", "Mercedes")
println(cars) // output: [BMW, Honda, Mercedes]
However, this is a bad idea because anyone can change the content of a MutableList any time:
cars[0] = "Renault"
println(cars) // output: [Renault, Honda, Mercedes]
If you want the content to stay the same, this can be a problem. List is immutable, so our content will not be changed. If you try to change it in a list, you will get an error:
val cars = listOf<String>("BMW", "Honda", "Mercedes")
cars[0] = "Renault" // ErrorInitialization
List is a generic type. As you saw from the previous examples, you can initialize it with the help of listOf<E>, where E is the type of elements contained in the list:
val textUsMethod = listOf<String>("SMS", "Email")
The type can also be derived from the context:
val textUsMethod = listOf("SMS", "Email")
If you need to initialize an empty list, you can use the method emptyList:
val staff = emptyList<String>()
println(staff) // output: []
Another way of creating a list is to call a builder function - buildList().
val names = listOf<String>("Emma", "Kim")
val list = buildList {
add("Marta")
addAll(names)
add("Kira")
}
println(list) // output: [Marta, Emma, Kim, Kira]Methods and properties
Let's recap the properties and methods of List:
sizereturns the size of yourList.isEmpty()shows whether the list is empty or not.
Also, List has a method get(index), which returns the element in that position. You can also use [index] to get an element. Remember that indexing starts with zero!
Let's assume you have a guest list for a party:
val partyList = listOf("Fred", "Emma", "Isabella", "James", "Olivia")
How do we know when it's time to start a party? Let's check if the guests are already there using the method isEmpty. If the party is not empty, we would like to know the number of guests and find out who gets the first welcome cocktail!
We will get something like this:
if (!partyList.isEmpty()) {
val size = partyList.size
val whoIsFirst = partyList[0]
println("The party will not be lonesome! We already got $size people. And $whoIsFirst was the first to arrive today!")
// The party will not be lonesome! We already got 5 people. And Fred was the first to arrive today!
}
Let's see how to work with other familiar methods:
indexOf(element)returns the index of the first occurrence of the specified element. If it isn't in the list, the function returns-1.contains(element)returnstrueif the element specified is in the list, andfalseif it's not.
Emma argued that she was entitled to the first cocktail. But is that so? Let's check:
println("Emma came in ${partyList.indexOf("Emma") + 1}") // Emma came in 2
Looks like Emma didn't come first, she actually came second. Now, James wants to know (as always) if Isabella has come:
println("Guys, is it true that Isabella came? It's ${partyList.contains("Isabella")}") // Guys, is it true that Isabella came? It's true
There are many other useful List methods: check out kotlinlang.org and get familiar with them!
Iterating through elements
You can iterate through elements in the List with the help of the for loop. Let's see an example:
val participants = listOf("Fred", "Emma", "Isabella")
for (participant in participants) {
println("Hello $participant!")
}
// Hello Fred!
// Hello Emma!
// Hello Isabella!
In this example, we iterate through the participants and print them to the console.
Idiom
The List is a very common structure in programming. Predictably, it has its own idiom.
You've already seen a few ways to create a List. As always, the Kotlin community recommends using the shortest way. You can find it on kotlinlang.org.
val list = listOf("a", "b", "c")Conclusion
Now you know the main difference between a List and a MutableList in Kotlin. Just to recap: use List when you don't want the content to change.
You know how to initialize a list, check if it's empty, see if it contains a certain element, get it by index or find out its index, and figure out its size. You can iterate through the elements of the List with the help of the for loop. This is not all, but it's enough to start you off! Let's move on to some practice tasks.