1. Overview
In this quick tutorial, we’ll explore how to convert a List into an Array in Kotlin. Further, we’ll discuss the preference for the choice between Arrays and ArrayList in our daily work.
We’ll use assertions in unit tests to verify the conversion result for simplicity.
2. Converting a List Into an Array
When we want to convert a List into an Array in Kotlin, the extension function Collection.toTypedArray() is the way. Let’s see an example:
val myList = listOf("one", "two", "three", "four", "five")
val expectedArray = arrayOf("one", "two", "three", "four", "five")
assertThat(myList.toTypedArray()).isEqualTo(expectedArray)
If we execute the test above, it passes. Since the toTypedArray is an extension function on the Collection interface, it’s available on all Collection objects, such as Set and List.
We know that in Kotlin, except for Array
val myList = listOf(1L, 2L, 3L, 4L, 5L)
val expectedArray = longArrayOf(1L, 2L, 3L, 4L, 5L)
assertThat(myList.toLongArray()).isEqualTo(expectedArray)
As we can see, these methods allow us to convert collections into primitive arrays easily.
3. Preferring Lists Over Arrays
We’ve seen that converting lists into arrays is not a hard job in Kotlin. Also, we know ArrayList and Array are pretty similar data structures.
So, a question may come up: When we work on a Kotlin project, how should I choose between List and Array? The section’s title gives away the answer: We should prefer Lists over Arrays.
Next, let’s discuss why we should prefer Lists.
Compared to Java, Kotlin has made quite some improvements to Arrays — for example, introducing primitive type arrays, generic support, and so on. However, we still should prefer List/MutableList over Array. This is because:
- Arrays are mutable – We should try to minimize mutability in our application. So, the immutable List should be our first choice.
- Arrays are fixed-size – We cannot resize an array after creating it. However, on the other side, adding or removing elements to a MutableList is pretty easy.
- Array
is invariant – For example, val a : Array = Array doesn’t compile (Type mismatch). However, List(1) { 42 } is covariant: val l: List = listOf(42, 42, 42) is fine. - Lists/MutableLists have more functionalities than arrays, and their performance is almost as good as arrays.
Therefore, preferring Lists over Arrays is a good practice unless we’re facing a performance-critical situation.
4. Conclusion
In this article, we’ve learned how to convert a List into an Array in Kotlin. Moreover, we’ve discussed why we should prefer Lists over Arrays in our daily usage.
As always, the full source code used in the article can be found over on GitHub.