— Kotlin, MutableList, Android Development — 1 min read
In Kotlin, the List
interface represents an immutable collection of elements, while MutableList
provides a collection that can be modified. There are situations where you may need to convert a List
into a MutableList
to perform operations like adding, removing, or updating elements. This article will guide you through the process of converting a List
to a MutableList
in Kotlin, with examples focused on Android development.
To convert a List
to a MutableList
, you can use the toMutableList()
function provided by the Kotlin standard library. This function creates a new MutableList
containing the same elements as the original List
.
Here's an example:
1val list: List<Int> = listOf(1, 2, 3, 4, 5)2val mutableList: MutableList<Int> = list.toMutableList()3
4mutableList.add(6)5mutableList.remove(3)6
7println(mutableList) // Output: [1, 2, 4, 5, 6]
In the example above, we first create a List
called list
containing integers from 1 to 5. We then use the toMutableList()
function to convert it into a MutableList
called mutableList
. After the conversion, we can perform mutable operations on mutableList
, such as adding element 6 and removing element 3.
When working with Android development, you might often encounter scenarios where you need to convert a List
to a MutableList
. Let's take an example of converting a list of strings obtained from a database query into a MutableList
for displaying data in a RecyclerView.
Assuming you have obtained a list of user names from a database query:
1val userList: List<String> = getUserNamesFromDatabase()2val mutableUserList: MutableList<String> = userList.toMutableList()
In this example, getUserNamesFromDatabase()
retrieves a list of user names from a database query, which is initially returned as a List
. By calling toMutableList()
, we convert it into a MutableList
named mutableUserList
. You can now use mutableUserList
to populate a RecyclerView adapter or perform any other required modification.
Converting a List
to a MutableList
in Kotlin is a straightforward process using the toMutableList()
function provided by the Kotlin standard library. This allows you to transform an immutable collection into a mutable one, enabling you to make changes like adding or removing elements. In Android development, converting a List
to a MutableList
is useful when dealing with data obtained from queries or external sources that require modification.