KT.DOUBLE_MUTABILITY_FOR_COLLECTION

Using var when declaring a mutable collection

Using var when declaring a mutable collection leads to double mutability. Consider instead declaring your variable with val or switching your declaration to use an immutable type.

Noncompliant Code

Copy
var myList = mutableListOf(1,2,3)
var mySet = mutableSetOf(1,2,3)
var myMap = mutableMapOf("answer" to 42)

Compliant Code

Copy
// Use val
val myList = mutableListOf(1,2,3)
val mySet = mutableSetOf(1,2,3)
val myMap = mutableMapOf("answer" to 42)

// Use immutable types
var myList = listOf(1,2,3)
var mySet = setOf(1,2,3)
var myMap = mapOf("answer" to 42)

Options

  • mutableTypes (default: ['kotlin.collections.MutableList', 'kotlin.collections.MutableMap', 'kotlin.collections.MutableSet', 'java.util.ArrayList', 'java.util.LinkedHashSet', 'java.util.HashSet', 'java.util.LinkedHashMap', 'java.util.HashMap'])

    Define a list of mutable types to trigger on when defined with 'var'.

The content on this page is adapted from the Detekt Docs. Copyright ©2022 The Detekt Team. All rights reserved. https://detekt.dev/comments.html