Search code examples
androidkotlinarraylistmutablelist

Remove element from mutable list - removeIf


    private var cardsList: MutableList<SomeObject>? = null
    val condition = Predicate<SomeObject> {
        it.id() == cardId
    }

    cardsList?.toMutableList()?.removeIf(condition)

    getNavigator()?.initRecycleView(cardsList)

I have one element in list; I have verified the id to be the same as cardId.

When I run the above code i expect that after removeIf is called, the cardsList will be empty, but it still has one element.

removeIf() returns true when called with condition.

I don't get it.


Solution

  • You are not actually deleting anything from cardsList.
    cardsList?.toMutableList() creates another mutable list object and deletes from that.
    You should do:

    cardsList?.removeIf(condition)
    

    Edit from your comment.
    I suspect that although you have declared cardsList to be MutableList somewhere along the way you did something like:

    cardsList = listOf(...) as MutableList<SomeObject>
    

    and so cardsList is not actually a mutable list.
    If this is the case then before you remove the item do this:

    cardsList = cardsList?.toMutableList()
    

    and then:

    cardsList?.removeIf(condition)