0

I have a function that takes a List as a parameter and the aim is to merge this list with another list contained in an object.

private fun joinListToUpdatedList(listToJoin: List<ExpirationDatesArt>?){

        val folderUpdatedListValue : MutableList<ExpirationDatesArt>? = folderUpdatedList.ExpirationDatesArt?.toMutableList()

        if(listToJoin != null){
            if(folderUpdatedListValue != null){

                folderUpdatedListValue.addAll(listToJoin)
                val joinedUpdatedList = folderUpdatedListValue.distinctBy { it.cdean }

                folderUpdatedList.ExpirationDatesArt = joinedUpdatedList
            }
            else{
                folderUpdatedList.ExpirationDatesArt = listToJoin
            }
        }
    }

When I first call the function, my object's list is null, so its value is initialized with listToJoin.

If I call the function a second time, whether immediately or several seconds later, the folderUpdatedListValue initialization crashes and returns a ConcurrentModificationException error.

I don't understand why, because I'm not deleting an item, I'm just trying to access the list of the object I'm interested in.

I tried to use addAll function on listToJoin with folderUpdatedListValue but the result is the same.

How can I enable this function to be called several times?

Quentin
  • 486
  • 4
  • 20
  • i think it's missing a collect() after distinctBy(). Type inferance issue – Volzy Aug 01 '23 at 13:42
  • 1
    The issue is that you are having to iterate the `folderUpdatedList.ExpirationDatesArt` to create the copy so there must be some other place in code outside this function that is opening an iterator on it without completing iteration. – Tenfour04 Aug 01 '23 at 13:50
  • 2
    Unrelated, but IMO it is an anti-pattern for a function to be no-op when an argument is null. It should just make the argument non-nullable and push it to the caller to only call if it’s non-null instead of the function silently failing to do anything. Also, your entire function contents can be simplified to `folderUpdatedList.ExpirationDatesArt = (folderUpdatedList.ExpirationDatesArt.orEmpty() + listToJoin.orEmpty()).distinctBy { it.cdean }` – Tenfour04 Aug 01 '23 at 13:52

0 Answers0