Using Mutable list in kotlin

Divya Dharshini
1 min readJul 3, 2021

--

list vs mutable list

List is Read only

Mutable list can be modified Read/Add/Remove

Syntax & Example

List creation. var listItems: List<Any> = emptyList()

Mutablelist creation val mutable = mutableListOf<String>()

convert list to mutable list

To add/remove/reorder the list

val mutable = normalList.toMutableList()

To add normalList.toMutableList().apply {

this.add(object)

}.toList()

Real app scenarios

  1. API responses need to be modified before rendering to UI. Like

Change the order — e.g.Moving recent item to Top

2. Single list can be used to load values from different APIs

1st API call -> response loaded to list

2nd API call -> To the existing list at any position you can modify.(allocate at end, afterThirdElement, beforeFirstElement)

Example

Move/Reorder item to the end of list

val itemsTobeMoved = normalList.filter { it is Object ) }

val updatedList = normalList.toMutableList().apply {

this.removeAll(itemsTobeMoved)

this.addAll(itemsTobeMoved)

}.toList()

Add item to particular position

fun allocateAtThirdPosition(normalList: List<Any>, itemToBeAdded: Any):List<Any> =

normalList.toMutableList().apply {this.add(3, itemToBeAdded)}.toList()

--

--