Search code examples
androidkotlinmutablelist

Android Kotlin - find in MutableList and set condition


This is the code for changing a value in a mutable list in case it is found:

vids?.find { it.id == 2 }?.iLike = true

But how to set a condition in case it wasn't found? I know how to do this in for loops so don't answer with that :D


Solution

  • You have to validate if it's found and then return

    vids?.find { it.id == 2 }?.let {
        it.iLike = true
    } ?: run {
        //do something
    }
    

    Just a clarification, you are not changing the value of the element because the list is mutable but because the attribute on the type of the collection is mutable. The attribute iLike is mutable that is why you can change it, not because of the mutable list.