Topic Overview and Actualization

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!

Introduction to Lists in 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:

    val myToDoList = listOf("buy groceries", "take out the trash", "send emails")

Depending on the requirements, Lists can be mutable (modifiable using mutableListOf()) or immutable (non-modifiable with listOf()).

Creating Lists in Kotlin

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:

val names = listOf("Alice", "Bob", "Charlie")  // An immutable list
names.add("Dave") // This will cause an error because list is immutable

val mutableNames = mutableListOf("Alice", "Bob", "Charlie")  // A mutable list
mutableNames.add("Dave")  // Adding an element to the mutable list

In this context, add() is a method that allows us to add more elements to a mutable list.

Accessing List Elements

Accessing elements in a list is achieved using numeric indices. Remember, list indexing starts at 0:

val fruits = listOf("Apple", "Banana", "Cherry")
println(fruits[0])  // Accessing the first element, "Apple"
println(fruits[2])  // Accessing the third element, "Cherry"

Exercise caution! Attempting to access an index not present in the list will throw an IndexOutOfBoundsException.

Properties of Lists

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:

val numbers = listOf(1, 2, 3, 4, 5)
println(numbers.size)  // Size of the list, prints 5

val colors = listOf("Red", "Green", "Blue")
println(colors.first())  // First element, prints "Red"
println(colors.last())  // Last element, prints "Blue"

val planets = listOf("Mercury", "Venus", "Earth")
println(planets.indexOf("Venus"))  // Index of "Venus", prints 1

These properties empower our coding arsenal!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal