kotlin convert list to mutable list
To convert a list to a mutable list in Kotlin, you can follow these steps:
- Declare a list of elements: Start by declaring a list of elements using the
listOf()
function. For example:
val list = listOf(1, 2, 3, 4, 5)
- Create a mutable list: Next, create a mutable list by using the
toMutableList()
function and assigning it to a new variable. This function will convert the existing list to a mutable list. For example:
val mutableList = list.toMutableList()
- Modify the mutable list: Now, you can modify the mutable list by adding, removing, or updating its elements. Since it is mutable, you can perform any changes you need. For example, you can add a new element using the
add()
function:
mutableList.add(6)
- Access the modified mutable list: You can access the modified mutable list and perform any further operations on it. For example, you can print the elements of the mutable list using a loop.