Kotlin List Tutorial šŸŽÆ

beginner
15 min

Kotlin List Tutorial šŸŽÆ

Welcome to the Kotlin List tutorial! In this comprehensive guide, we'll dive into the world of lists in Kotlin, a modern and easy-to-learn programming language. By the end of this tutorial, you'll be able to handle lists confidently, and you'll understand how they can be used in real-world projects.

What is a List in Kotlin? šŸ“

A list in Kotlin is a collection of elements, which can be of different types. Lists are ordered and allow duplicate elements. Think of a list as a container that holds multiple items in a specific order.

Creating a List šŸ’”

Let's create our first list! You can create a list in Kotlin using the listOf() function or the arrayOf() function. Here's an example:

kotlin
val fruits = listOf("Apple", "Banana", "Orange") val numbers = arrayOf(1, 2, 3, 4)

šŸ“ Note: listOf() returns an immutable list, meaning you cannot change its elements. On the other hand, arrayOf() returns a mutable array, allowing you to modify its elements.

Accessing List Elements šŸ’”

To access list elements, you can use the index number within square brackets []. Here's an example:

kotlin
println(fruits[0]) // Output: Apple

List Operations šŸ’”

Kotlin provides several built-in functions to work with lists, such as size, contains, indexOf, and lastIndexOf. Let's take a look at a few examples:

kotlin
println(fruits.size) // Output: 3 println(fruits.contains("Apple")) // Output: true println(fruits.indexOf("Apple")) // Output: 0 println(fruits.lastIndexOf("Apple")) // Output: 0

Modifying a List šŸ’”

Since we've created an immutable list using listOf(), you cannot modify its elements directly. To create a mutable list, use the mutableListOf() function instead:

kotlin
val fruits = mutableListOf("Apple", "Banana", "Orange") fruits.add("Mango") // Adding an element fruits[0] = "Pineapple" // Replacing an element

List Functions šŸ’”

Kotlin offers several functions to manipulate lists, such as map, filter, sort, and more. Let's explore a few examples:

kotlin
val uppercaseFruits = fruits.map { it.toUpperCase() } println(uppercaseFruits) // Output: [PINEAPPLE, Banana, ORANGE, MANGO] val filteredFruits = fruits.filter { it.startsWith("P") } println(filteredFruits) // Output: []

šŸ“ Note: map transforms each element in the list, and filter returns a new list containing only the elements that match the provided condition.

Common List Types šŸ“

There are two common list types in Kotlin: List<T> and MutableList<T>. The List<T> type represents an immutable list, while MutableList<T> represents a mutable list.

Quiz šŸ’”

Quick Quiz
Question 1 of 1

What is Kotlin List?

Stay tuned for more advanced Kotlin List concepts! In the next lesson, we'll delve deeper into working with lists, including sorting, searching, and merging lists. See you then! šŸš€