Augmented Assign On Read-only Collection

ID

kotlin.augmented_assign_readonly_collection

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Kotlin

Tags

efficiency, reliability

Description

Reports += / -= augmented-assignment statements whose left-hand side is declared as a Kotlin read-only collection interface (List, Set, Map, Collection, Iterable). On a read-only collection, += compiles to xs = xs.plus(…​), allocating a fresh collection on every call. The mutable counterparts implement true in-place plusAssign operators with amortised constant cost.

Rationale

var xs: List<Int> = listOf(1)
xs += 2                       // FLAW — allocates a new List

val xs: MutableList<Int> = mutableListOf(1)
xs += 2                       // OK — in-place mutation

The silent allocation is doubly problematic: it costs O(N) per operation inside a loop, and it changes object identity, so any consumer that captured the original reference now sees a stale snapshot.

Remediation

Pick the interface that matches the intended semantics:

  • Declare the variable as MutableList, MutableSet, or MutableMap to enable in-place mutation.

  • Or make the reassignment explicit: xs = xs + 2 — same allocation cost but the intent is no longer hidden behind the operator.