Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 19, 2024
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.
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<T>, we have primitive type array types, such as IntArray, LongArray, and more. As primitive type arrays are more efficient than their typed arrays, we should prefer using the primitive type arrays. Kotlin has provided different convenient extension functions on the corresponding Collection<Primitive_Type> interfaces, for example Collection<Long>.toLongArray():
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.
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:
Therefore, preferring Lists over Arrays is a good practice unless we’re facing a performance-critical situation.
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.