Collections in Kotlin

Suneet Agrawal
2 min readApr 28, 2021

--

Collections are a common concept for most programming languages. It is a way of storing similar data types in a single object and iterate over it. Similar to any other language, Kotlin also has Collection defined in kotlin.collections package.

This post was originally posted at https://agrawalsuneet.github.io/blogs/collections-in-kotlin/ and reposted on Medium on 28th April 2021.

Types of Collection in Kotlin

There are two types of collection in Kotlin

  1. Immutable
    The one which can’t be modified once the object is created. We can just iterate over them or create a copy of them but we can’t modify the actual one.
  2. Mutable
    These can be modified means that we can add items or elements to the original object once they are created along with iteration and copy.

To understand the immutable and mutable types, Let’s try to understand the interfaces in the Collection package of Kotlin first.

Keep in mind we are only talking about the interfaces and implementations of Kotlin. Although, Android is compatible with Java also and we can use the Collections of Java also defined in java.util package but Kotlin has a separate Collection and a few of the implementations like Vector, CopyOnWriteArrayList, CopyOnWriteArraySet and many more are not there in Kotlin.

Iterable

The parent of all the interfaces is Iterable. As the name suggests, it confirms the functionality of iteration by the class which implements it. This has an abstract function iterator that returns the Iterator reference object.

/**
* Classes that inherit from this interface can be represented as a sequence of elements that can
* be iterated over.
* @param T the type of element being iterated over. The iterator is covariant on its element type.
*/
public interface Iterable<out T> {
/**
* Returns an iterator over the elements of this object.
*/
public operator fun iterator(): Iterator<T>
}

Please continue reading at https://agrawalsuneet.github.io/blogs/collections-in-kotlin/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--