A collection is changed while a loop iterates over it, which throws ConcurrentModificationException

tx0/kotlin:mutation-during-iterationdefaulterrorreliability/collectionsdepth fastbug

What it finds

for (item in items) { if (item.done) items.remove(item) } changes items under its own iterator: the next step throws ConcurrentModificationException, or skips elements. removeAll, removeIf or an explicit iterator with iterator.remove() do it safely.

Reported for add, remove, removeAt, addAll, removeAll, clear and put on the variable iterated by a for loop or by forEach, unless the loop is left right after the change with break or return.

From the rule's source, modified_while_iterating.rs.

Example from the rule's tests
fun prune(items: MutableList<Item>, other: MutableList<Item>) {    for (item in items) {        if (item.done) items.remove(item)tx0 reports: items is changed while it is being iterated        other.add(item)    }    items.forEach {        if (it.done) items.add(it)tx0 reports: items is changed while it is being iterated    }    for (item in items) {        if (item.done) {            items.remove(item)            break        }    }    items.removeAll { it.done }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/kotlin:mutation-during-iteration" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/kotlin:mutation-during-iteration] reason="..."

tx0 explain tx0/kotlin:mutation-during-iteration shows the same in the terminal. Found a false positive? Report it.