Skip to main content

How to convert an array to a list in Kotlin

How to convert an array to a list in Kotlin.

Here is a detailed step-by-step tutorial on how to convert an array to a list in Kotlin.

Step 1: Declare and initialize an array​

First, you need to declare and initialize an array in Kotlin. An array is a fixed-size collection of elements of the same type. You can declare an array by specifying the type of elements it will hold, followed by square brackets ([]), and then assign values to it using the arrayOf() function.

val array = arrayOf(1, 2, 3, 4, 5)

In this example, we have declared an array of integers and assigned it the values 1, 2, 3, 4, and 5.

Step 2: Convert the array to a list​

To convert an array to a list in Kotlin, you can use the toList() extension function. This function is available on the array object and returns a new list containing all the elements of the array.

val list = array.toList()

In this example, the array is converted to a list and assigned to the variable "list".

Step 3: Accessing the elements of the list​

Once you have converted the array to a list, you can access its elements using the indexing operator ([]). The indexing starts from 0, so the first element of the list can be accessed using index 0.

val firstElement = list[0]

In this example, we are accessing the first element of the list and assigning it to the variable "firstElement".

Step 4: Modifying the list​

After converting the array to a list, you can modify the list by adding, removing, or updating elements. Since the converted list is mutable, you can use standard list operations to modify it.

list.add(6) // Adds 6 to the end of the list
list.removeAt(0) // Removes the element at index 0 from the list
list[2] = 7 // Updates the element at index 2 to 7

In this example, we are adding the element 6 to the end of the list, removing the element at index 0, and updating the element at index 2 to 7.

Step 5: Iterate over the list​

You can iterate over the elements of the list using various looping constructs in Kotlin, such as for loop, while loop, or forEach loop.

for (element in list) {
println(element)
}

list.forEach { element ->
println(element)
}

var index = 0
while (index < list.size) {
println(list[index])
index++
}

In these examples, we are iterating over the elements of the list and printing them to the console using different looping constructs.

That's it! You have successfully converted an array to a list in Kotlin. Now you can use the list for further processing or manipulation as per your requirements.