Convert an array to a list in Kotlin
This article explores different ways to convert an array to a list using Kotlin.
1. Using toList() function
The standard way to convert an array to a list is with the extension function toList().
|
1 2 3 4 5 6 7 |
fun main() { val arr = arrayOf("A", "B", "C", "D") val list: List<String> = arr.toList() println(list) // [A, B, C, D] } |
It returns an immutable list instance. To get a mutable list, you can use the toMutableList() function.
|
1 2 3 4 5 6 7 |
fun main() { val arr = arrayOf("A", "B", "C", "D") val list: MutableList<String> = arr.toMutableList() println(list) // [A, B, C, D] } |
2. Using Spread Operator
You can also use the listOf() function using the Spread operator by prefixing the array with *.
|
1 2 3 4 5 6 7 |
fun main() { val arr = arrayOf("A", "B", "C", "D") val list = listOf(*arr) println(list) // [A, B, C, D] } |
3. Using asList() function
If you just need a wrapper over the original array, you can use the asList() function. It creates a fixed-size list backed by the specified array.
|
1 2 3 4 5 6 7 |
fun main() { val arr = arrayOf("A", "B", "C", "D") val list = arr.asList() println(list) // [A, B, C, D] } |
4. Using for loop
Another solution is to create an empty list and push every element of the specified array into the list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun <T> convert(arr: Array<T>): List<T> { val list: MutableList<T> = ArrayList() for (i in arr) { list.add(i) } return list } fun main() { val arr = arrayOf("A", "B", "C", "D") val list = convert(arr) println(list) // [A, B, C, D] } |
5. Using addAll() function
Instead of using the for-loop, you can use the addAll() to add all elements of the specified array to the list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun <T> convert(arr: Array<T>): List<T> { val list: MutableList<T> = ArrayList() list.addAll(arr); return list } fun main() { val arr = arrayOf("A", "B", "C", "D") val list = convert(arr) println(list) // [A, B, C, D] } |
That’s all about converting an array to a list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)