In Kotlin, a ‘List‘ is an immutable (read-only) collection of elements, whereas a ‘MutableList‘ is a mutable(collection of elements that can be modified) collection of elements. This means that once elements have been added to a ‘List‘, they cannot be modified, while a ‘MutableList‘ allows modification by adding, removing, or replacing elements.
Here is an example that shows the difference between a ‘List‘ and a ‘MutableList‘:
val list = listOf("apple", "banana", "orange") //immutable list
//To add an element in above list will give us an error -> error: unresolved reference add.
val mutableList = mutableListOf("apple", "banana", "orange") //mutable list
mutableList.add("pear") // we can add a new element to mutable list
In the above example, when defining ‘list‘, we use the ‘listOf()‘ function which creates an immutable list. We can try to add a new element to this list but this will result in a compilation error.
When defining ‘mutableList‘, we use the ‘mutableListOf()‘ function which creates a mutable list. We can use the ‘add()‘ method to add an element to this list.
To convert a ‘List‘ to a ‘MutableList‘, we can use the ‘toMutableList()‘ method which creates a new ‘MutableList‘ with the same elements as the original ‘List‘. Similarly, to convert a ‘MutableList‘ to a ‘List‘, we can use the ‘toList()‘ method which creates a new ‘List‘ with the same elements as the original ‘MutableList‘.
Here is an example that demonstrates how to convert between a ‘List‘ and a ‘MutableList‘:
val list = listOf("apple", "banana", "orange")
val mutableList = list.toMutableList() //converting List to MutableList
mutableList.add("pear")
val newlist = mutableList.toList() //converting MutableList to List
In the above example, we first create a ‘List‘ called ‘list‘. We then convert this ‘List‘ to a ‘MutableList‘ using the ‘toMutableList()‘ method and store the result in a variable called ‘mutableList‘. We then add a new element to ‘mutableList‘ using the ‘add()‘ method.
Finally, we convert ‘mutableList‘ back to a ‘List‘ using the ‘toList()‘ method and store the result in a variable called ‘newlist‘. This ‘newlist‘ is now an immutable list and cannot be modified.
Note that both ‘toList()‘ and ‘toMutableList()‘ create a new list, so if you have a large list, this could result in a performance overhead.