Home > OS >  Why set function in the mutableList not set the element? Kotlin
Why set function in the mutableList not set the element? Kotlin

Time:01-24

I am trying to switch old element from the list to a new element of the list and put it on the same spot as old one by index. But its not setting it

val foundIndex = todoItemList.value?.indexOfFirst { it.id == item.id }
    foundIndex?.let {
       val list = todoItemList.value?.toMutableList()
        list?.set(it, item)
    }

CodePudding user response:

// the comments below your question are rigth
// you just have to assign a new list to your `todoItemList` like this

val foundIndex = todoItemList.value?.indexOfFirst { it.id == item.id }
                foundIndex?.let {
val list = todoItemList.value?.toMutableList() // here you are creating a new instance of list - MutableList
   list?.set(it, item) // here you are working with your new list, setting item to foundIndex in a new list
}    
todoItemList.value = list // you have to assign your new list to todoItemList.value 
//in case if value in todoItemList's class declared as vaR not vaL, 

//otherwise you have to copy your whole todoItemList object with a new list, something like this 
todoItemList = TodoItemListClass(value = list)
  • Related