Hello, coding rookie! Today, we're venturing into Kotlin's vast terrain to unravel a fundamental feature: Lists! Much like a grocery list or a to-do list, Kotlin allows us to create a list of items. With our focus set on understanding Lists, we're prepared for an adventure into the land of Kotlin!
Have you ever created a to-do list? It organizes and stores your tasks, doesn't it? Kotlin provides the same functionality with Lists! Kotlin's Lists can store multiple items (of either similar or various types) similar to this to-do list:
Depending on the requirements, Lists can be mutable (modifiable using mutableListOf()) or immutable (non-modifiable with listOf()).
To create a list in Kotlin, we require the listOf() (for an immutable list) or the mutableListOf() (for a mutable list) function. Let's see how:
In this context, add() is a method that allows us to add more elements to a mutable list.
Accessing elements in a list is achieved using numeric indices. Remember, list indexing starts at 0:
Exercise caution! Attempting to access an index not present in the list will throw an IndexOutOfBoundsException.
Kotlin Lists come with useful properties. The size signifies the count of items, first and last refer to the first and last elements respectively, and indexOf fetches the index of a specified element:
These properties empower our coding arsenal!
