In this section we will give you a brief introduction to Collections in Kotlin. The concept of collections is not new to Kotlin. It is already present in many other programming languages. The Kotlin standard library provides a set of tools to create and manage collections.
What are collections?
A Collection is a group of objects of same type. The objects inside a collection are known as elements or items.
Suppose we want to store marks of students in a class and perform operations on it like finding maximum, minimum, average marks etc. we can use collections.
Array can be a good choice for the same but the size of array is fixed. Addition or deletion of some elements from array is not possible. Also, collections provide many other functionalities that we will discuss is this section.
There are three types of Collection present in Kotlin:
Kotlin standard library provides methods to create the objects of list, set and map. According to the requirement, each one of them can be a:
Immutable Collection (Read only)
Mutable Collection (Both read and write)
We will discuss lists, sets and maps in the separate tutorial. Let us first discuss about Mutable and Immutable collection types.
Immutable Collections are inherited from
Collection<T> interface which does not provides functionality to add or remove elements. In immutable collections, an element cannot be added, removed or altered after declaration. After defining the immutable collection, we can only read its elements.
The immutable collection is simply known as collection also.
As the name suggests, mutable collections allow both write and read operations. In mutable collections we can add, remove and alter the values of elements.
Mutable collections are inherited from
MutableCollection<T> interface which provides functionality to read and alter elements. They also inherits basic functionalities from corresponding Collection interfaces.
In this tutorial we discussed about basics of Collections and discussed about its types. From next tutorial, we will start discussing about List, Map and Set in detail.