Chapter 6.1 : Working with Collections in Kotlin (Android)

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.

The Kotlin 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.

You can see here that, I have used listOf function to declare a string list. To declare an object, you can assign type by List.

Another example to find the maximum and minimum in a collection of numbers.

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 MutableList.

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!!!

Summary

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.

Protected by Copyscape

Share on Facebook0Share on Google+0Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Pin on Pinterest0Share on Tumblr0Email this to someone