Skip to main content

Kotlin Collections: Arrays, Lists, and Maps

In this tutorial, we will be exploring three fundamental collections in Kotlin: Arrays, Lists, and Maps. These collections are pivotal data structures that you will use frequently when developing applications in Kotlin. By the end of this tutorial, you'll have a deep understanding of these collections, their differences, use-cases, and how to manipulate them effectively.

What are Collections?

In programming, a collection usually refers to a group of objects. These objects can be of the same type or different types. Kotlin, like many other programming languages, provides several types of collections to handle data. Today, we'll focus on Arrays, Lists, and Maps.

Arrays

An Array in Kotlin is a class that represents an array (fixed-size, homogeneous elements). It is represented by the class Array in Kotlin. This class has get and set functions, size property, and other member functions.

Creating Arrays

There are several ways to create arrays in Kotlin. Here are some examples:

val numbers = arrayOf(1, 2, 3, 4, 5) // Array of Int
val names = arrayOf("John", "Jane", "James") // Array of Strings
val mixed = arrayOf(1, "John", 4.5, 'A') // Array of Any

Accessing Array Elements

To access elements in an array, you use the index of the element. Array indices start from 0.

val names = arrayOf("John", "Jane", "James")
println(names[0]) // prints: John

Lists

A List in Kotlin is an interface that extends the Collection interface. Lists store elements in a specified order and provide indexed access to them.

Creating Lists

Lists can be created using the listOf function for read-only lists or mutableListOf for mutable lists.

val readOnlyList = listOf("John", "Jane", "James")
val mutableList = mutableListOf("John", "Jane", "James")

Accessing List Elements

You can access elements of a list just like you do with arrays.

val names = listOf("John", "Jane", "James")
println(names[0]) // prints: John

Maps

A Map in Kotlin is an interface that extends the Collection interface. It stores key-value pairs. Each key is unique, and it is associated with exactly one value.

Creating Maps

You can create a map using the mapOf function for read-only maps or mutableMapOf for mutable maps.

val readOnlyMap = mapOf("name" to "John", "age" to 23)
val mutableMap = mutableMapOf("name" to "John", "age" to 23)

Accessing Map Elements

To access the values in a map, you can use the keys.

val person = mapOf("name" to "John", "age" to 23)
println(person["name"]) // prints: John

Conclusion

Arrays, Lists, and Maps are some of the most commonly used collections in Kotlin. They provide a convenient way to store, access, and manipulate groups of objects. By understanding these collections, you will be able to create more efficient and effective Kotlin applications.

In the next tutorial, we will explore how to manipulate these collections using Kotlin's powerful collection functions. Happy coding!