Write a Kotlin Program to Convert List to Array and Vice-Versa

In Kotlin, we can easily convert a List to an Array and vice-versa.

In this tutorial, we will discuss how to perform these conversions in Kotlin.

Converting a List to an Array

To convert a List to an Array, we can use the toTypedArray() function. The toTypedArray() function creates a new array and copies the elements of the List to the new array.

Here’s an example:

fun main() {
    val list = listOf("apple", "banana", "orange")
    val array = list.toTypedArray()

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

In this example, we have a List of fruits and we want to convert it to an Array.

We use the toTypedArray() function to convert the List to an Array. We then use a for loop to print each element of the Array.

Converting an Array to a List

To convert an Array to a List, we can use the toList() function.

The toList() function creates a new List and copies the elements of the Array to the new List.

Here’s an example:

fun main() {
    val array = arrayOf("apple", "banana", "orange")
    val list = array.toList()

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

In this example, we have an Array of fruits and we want to convert it to a List.

We use the toList() function to convert the Array to a List. We then use a for loop to print each element of the List.

In conclusion, converting a List to an Array or an Array to a List in Kotlin is very easy.

We can use the toTypedArray() function to convert a List to an Array and the toList() function to convert an Array to a List.

These functions create new data structures and copy the elements of the original data structure to the new one.