Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Kotlin Lists Tutorial

Introduction to Lists

In Kotlin, a list is a collection that holds a sequence of elements. Lists can contain duplicates and preserve the order of insertion. Kotlin provides various types of lists, including mutable and immutable lists.

Types of Lists

1. Immutable Lists

Immutable lists are read-only and cannot be modified after they are created. You can create an immutable list using the listOf() function.

Example:

val fruits = listOf("Apple", "Banana", "Cherry")
fruits: [Apple, Banana, Cherry]

2. Mutable Lists

Mutable lists can be modified (elements can be added or removed). You can create a mutable list using the mutableListOf() function.

Example:

val vegetables = mutableListOf("Carrot", "Potato")
vegetables: [Carrot, Potato]

Creating Lists

Creating lists in Kotlin is straightforward. Here’s how you can create both immutable and mutable lists:

Immutable List Creation:

val numbers = listOf(1, 2, 3, 4, 5)

Mutable List Creation:

val moreNumbers = mutableListOf(6, 7, 8)

Accessing Elements

You can access elements in a list using their index. The index is zero-based, meaning the first element is at index 0.

Example of Accessing Elements:

val firstFruit = fruits[0]
firstFruit: Apple

Modifying Mutable Lists

With mutable lists, you can add, remove, or update elements.

Adding Elements

Example of Adding Elements:

vegetables.add("Tomato")
vegetables: [Carrot, Potato, Tomato]

Removing Elements

Example of Removing Elements:

vegetables.remove("Potato")
vegetables: [Carrot, Tomato]

Updating Elements

Example of Updating Elements:

vegetables[0] = "Cucumber"
vegetables: [Cucumber, Tomato]

Common List Operations

Kotlin provides various functions to manipulate lists:

1. Iterating through a List

Example of Iterating Through a List:

for (fruit in fruits) { println(fruit) }

2. Filtering a List

Example of Filtering a List:

val filtered = fruits.filter { it.startsWith("A") }
filtered: [Apple]

3. Mapping a List

Example of Mapping a List:

val upperCaseFruits = fruits.map { it.toUpperCase() }
upperCaseFruits: [APPLE, BANANA, CHERRY]

Conclusion

Lists in Kotlin are versatile and easy to use. Understanding how to work with both immutable and mutable lists will greatly enhance your programming skills in Kotlin. Always remember the differences between the two types and utilize the various functions available for list manipulation.