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.
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.
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:
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.
To access list elements, you can use the index number within square brackets []. Here's an example:
println(fruits[0]) // Output: AppleKotlin 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:
println(fruits.size) // Output: 3
println(fruits.contains("Apple")) // Output: true
println(fruits.indexOf("Apple")) // Output: 0
println(fruits.lastIndexOf("Apple")) // Output: 0Since we've created an immutable list using listOf(), you cannot modify its elements directly. To create a mutable list, use the mutableListOf() function instead:
val fruits = mutableListOf("Apple", "Banana", "Orange")
fruits.add("Mango") // Adding an element
fruits[0] = "Pineapple" // Replacing an elementKotlin offers several functions to manipulate lists, such as map, filter, sort, and more. Let's explore a few examples:
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.
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.
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! š