Kotlin Array.toMutableList() Tutorial
The Array.toMutableList()
function in Kotlin is used to convert an array to a mutable list. It creates a new mutable list containing the elements of the original array.
Array.toMutableList() function is useful when you need to modify the elements of the collection, as a mutable list allows for adding, removing, and updating elements.
This tutorial will explore the syntax of the Array.toMutableList()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the Array.toMutableList()
function is as follows:
fun <T> Array<out T>.toMutableList(): MutableList<T>
Example for Array toMutableList() function
In this example, we’ll take an array of string elements in colorsArray
, and use toMutableList()
to convert the given array of strings to a mutable list.
Kotlin Program
fun main() {
val colorsArray = arrayOf("red", "green", "blue", "yellow")
// Using toMutableList() to convert the array of strings to a mutable list
val mutableColorsList = colorsArray.toMutableList()
// Printing the original array and the resulting mutable list
println("Input Array:\n${colorsArray.contentToString()}\n")
println("Output Mutable List:\n$mutableColorsList")
}
Output
Input Array:
[red, green, blue, yellow]
Output Mutable List:
[red, green, blue, yellow]
Summary
In this tutorial, we’ve covered the Array.toMutableList()
function in Kotlin, its syntax, and how to use it to convert an array to a mutable list.