Double Mutability Collection

ID

kotlin.double_mutability_collection

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Kotlin

Tags

collections, mutability

Description

Reports var property declarations whose explicit type is a mutable collection (MutableList, MutableSet, MutableMap, etc.).

A var property can be reassigned, and a mutable collection can be mutated in-place. Combining both in one declaration allows callers to do either, which usually means neither intent was clearly stated.

Rationale

// Bad — callers can both reassign and mutate
var items: MutableList<Int> = mutableListOf(1, 2, 3)  // FLAW

// Good — in-place mutation only
val items: MutableList<Int> = mutableListOf(1, 2, 3)

// Good — reassignment only (snapshot semantics)
var items: List<Int> = listOf(1, 2, 3)

Remediation

Choose one form of mutability:

  • Use val with a mutable collection when only in-place mutation is needed.

  • Use var with an immutable collection when reassignment to a new snapshot is the intent.