Skip to main content

How to convert a list to an array in Kotlin

How to convert a list to an array in Kotlin.

Here's a step-by-step tutorial on how to convert a list to an array in Kotlin:

Step 1: Create a List

First, you need to create a list in Kotlin. You can do this by using the listOf() function and providing the elements of the list as arguments. Here's an example:

val list = listOf("apple", "banana", "orange")

Step 2: Convert the List to an Array

To convert the list to an array, you can use the toTypedArray() function. This function is available on the List interface and converts the list to an array of the specified type. Here's an example:

val array = list.toTypedArray()

Step 3: Accessing Elements in the Array

Once you have converted the list to an array, you can access its elements using the indexing operator ([]). The index starts from 0, so the first element is at index 0, the second element is at index 1, and so on. Here's an example:

val firstElement = array[0]
val secondElement = array[1]

Step 4: Modifying Elements in the Array

If you need to modify elements in the array, you can use the indexing operator to assign a new value to a specific element. Here's an example:

array[0] = "grape"

Step 5: Iterating Over the Array

To iterate over the elements in the array, you can use a for loop. Here's an example:

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

Step 6: Array of Primitive Types

If you want to convert a list of primitive types (such as Int, Double, etc.) to an array, you can use the toIntArray(), toDoubleArray(), and other similar functions. Here's an example:

val list = listOf(1, 2, 3)
val array = list.toIntArray()

That's it! You have successfully converted a list to an array in Kotlin. Remember to use the appropriate function based on the type of elements in your list.

I hope this tutorial was helpful.