In this very short tutorial, we’re going to learn a few ways to convert arrays to lists in Kotlin.
We will categorize these approaches into two groups: the ones that copy the original elements and the ones without copying.
2. Convert by Copying
val array = intArrayOf(1, 2, 3, 4) val list = array.toList() assertEquals(listOf(1, 2, 3, 4), list)
Since it’s a List, we won’t be able to mutate it after conversion. If we need to modify the list later on, we should use the toMutableList() extension function:
val array = intArrayOf(1, 2, 3, 4) val mutable = array.toMutableList() assertEquals(listOf(1, 2, 3, 4), mutable) mutable.add(5) assertEquals(listOf(1, 2, 3, 4, 5), mutable)
As shown above, after conversion, we added one element to the converted list. This is possible because this function returns an instance of MutableList instead of a plain List.
2.1. Link and Complexity
Both functions are copying the array values to the new list. Therefore, there are no lingering links between the array and the list after the conversion. That means if we change the array elements, that change won’t be reflected on the converted list:
array = 0 assertEquals(listOf(1, 2, 3, 4), list) // list didn't change
Moreover, the time and space complexity for the conversion algorithm would be O(n), as we need to copy all elements from the source array.
3. Convert by Wrapping
If we want to maintain a reference between the array and the converted list, we should use the asList() function:
val array = intArrayOf(1, 2, 3, 4) val list = array.asList() assertEquals(listOf(1, 2, 3, 4), list)
This function creates a new list backed by the original array. So, any change on the array will affect the converted list:
array = 0 assertEquals(listOf(0, 2, 3, 4), list)
Also, the conversion algorithm runs in O(1) from both time and space complexity perspectives.
In this tutorial, we saw how to convert a Kotlin Array to its corresponding List or MutableList.
The asList() function will reuse the original array, so it’s going to have a better footprint in terms of speed and memory usage. However, it may cause some confusion because of the link between the original array and the converted list. As always, we have to beware of these subtle differences and choose the right tool for the job!
As usual, all the examples are available over on GitHub.