In this tutorial, we will learn about mutable and immutable collections in Kotlin, their differences, benefits and drawbacks, and when to use which type.
By the end of this tutorial, you should be able to understand:
A basic understanding of the Kotlin programming language is required. Familiarity with general programming concepts such as variables, data types, and control structures will also be beneficial.
In Kotlin, a collection is a group of items stored in a single unit. You can have collections of integers, strings, custom objects, etc. Collections can be either mutable (changeable) or immutable (unchangeable).
Mutable collections are collections that can be altered after they have been created. This means you can add, remove, or change elements in the collection.
// Declaration of mutable list
var mList: MutableList<Int> = mutableListOf(1, 2, 3, 4)
mList.add(5) // mList now contains [1, 2, 3, 4, 5]
Immutable collections, on the other hand, cannot be altered after their creation. Once an element is added to the collection, it cannot be removed or changed.
// Declaration of immutable list
val iList: List<Int> = listOf(1, 2, 3, 4)
While mutable collections offer more flexibility, they can lead to increased bugs and harder-to-maintain code if not used carefully. Immutable collections, on the other hand, are safer and more predictable. It's generally a good practice to use immutable collections by default, and only use mutable collections when necessary.
var mList: MutableList<Int> = mutableListOf(1, 2, 3)
mList.add(4) // You can add elements
println(mList) // Outputs: [1, 2, 3, 4]
val iList: List<Int> = listOf(1, 2, 3)
// iList.add(4) // This would cause a compile error. You cannot add elements to an immutable list.
println(iList) // Outputs: [1, 2, 3]
We have learned:
For further learning, you can explore more about collection operations, such as filtering, mapping, and reducing. You can also learn about different types of collections, such as sets and maps.
Create a mutable list of strings and add 5 elements to it.
var mList: MutableList<String> = mutableListOf()
mList.add("one")
mList.add("two")
mList.add("three")
mList.add("four")
mList.add("five")
println(mList) // Outputs: [one, two, three, four, five]
Create an immutable list of integers and try to add an element to it. What happens?
val iList: List<Int> = listOf(1, 2, 3)
// iList.add(4) // This would cause a compile error. You cannot add elements to an immutable list.
println(iList) // Outputs: [1, 2, 3]
Trying to add an element to an immutable list results in a compile error.
For further practice, try working with different types of collections and perform various operations on them.