In this article, you will learn about collections in Kotlin. How to deal with Mutable and Immutable lists.
Before moving to current topic, I explained Kotlin from beginning and you can find full list of previous tutorial at Kotlin page.
In previous articles, we have learned about variables, operators, classes and functions. Now it is time to dig deep.
Kotlin provide facility to distinguishes mutable and immutable collections like lists, sets, maps etc. Control over such list is very much important to design good APIs and reduce bugs.
List<out T> type is an interface that provides read-only operations like size, get and so on. Like in Java, it inherits from
Collection<T> and that in turn inherits from
Iterable<T>. Methods that change the list are added by the
MutableList<T> interface. This pattern holds also for
Set<out T>/MutableSet<T> and
Map<K, out V>/MutableMap<K, V>.
More of Java
Kotlin is providing same functionality to use collection as in Java. But it is providing extended API which is very much helpful to boost up your coding speed.
Let’s see an examples of getting the last element in a list.
val stringList: List<String> = listOf("First", "Second", "Third")
println("Last Element is : " + stringList.last())
//Last Element is : Third
You can see here that, I have used
listOf function to declare a string list. To declare an object, you can assign type by
Another example to find the maximum and minimum in a collection of numbers.
val numbers: Collection<Int> = setOf(1, 14, 2, 15, 3)
println("Maximum is : " + numbers.max())
println("Mininum is : " + numbers.min())
//Maximum is : 15
//Minimum is : 1
Mutable vs Immutable List
As stated above, you can work with both mutable and immutable list to create more robust code. To work with mutable object, create a list by
mutableListOf and declare your object with
val numbers: MutableList<Int> = mutableListOf(11, 12, 13)
val readOnlyView: List<Int> = numbers
println(numbers) // prints "[11, 12, 13]"
println(readOnlyView) // prints "[11, 12, 13, 14]"
// -> does not compile .. Unresolved reference: clear
So you can see here that, you can modify and perform any kind of operations on MutableList but not on immutable list. As when you perform that it won’t compile. This is very much useful when you are suppose to print or perform any calculation with help of list but do not want to modify it. In SDK or API, this will give more control where you can modify and where not.
This is amazing!!!
In this article, you learned how to start with collection. You also learnt about mutable and immutable list. In next article, we will move on more deep in collection part.
Thanks for reading. Please ask any doubts in the comment. Don’t forget to share this article.