Skip to main content

Mutable collections in public API

DiagnosticMUTABLE_COLLECTION_PUBLIC_API
Default severityError
Gradle propertymutableCollectionPublicApi
Exemption@IntentionallyMutableCollection

What it reports​

Mutable types in public API return types, property types, value and context parameters, and type parameter bounds. The check includes nested type arguments and expanded type aliases.

It reports:

  • MutableList, MutableSet, and MutableMap.
  • MutableCollection, MutableIterable, MutableIterator, and MutableListIterator.
  • MutableMap.MutableEntry.
  • Implementations of these interfaces, such as ArrayList.
  • Array and primitive or unsigned array types.
public fun produce(): MutableList<String> = mutableListOf()

Rationale​

A mutable signature doesn't state who owns the collection or whose state a mutation changes. Use read-only types unless mutation is part of the contract.

Don't​

public class Holder(
public val items: MutableList<Int>,
)

Do​

public class Holder(
public val items: List<Int>,
)

Notes​

The check skips:

  • The array of a vararg parameter. The check still reports mutable element types.
  • Extension receivers, including function-type receivers such as MutableList<Int>.() -> Unit.
  • Overrides.
  • @PublishedApi internal declarations.

A read-only type can still refer to a mutable collection. Copy input collections when callers must not change stored values.

Exemption​

If this is intended, apply @IntentionallyMutableCollection to the declaration, parameter, or type usage.

Use the exemption when the declaration is part of the API design or must stay for backwards compatibility.

public class Holder(
@IntentionallyMutableCollection(reason = ExemptionReason.API_DESIGN)
public val items: MutableList<Int>,
)

Configuration​

build.gradle.kts
apiWatchdog {
mutableCollectionPublicApi = WatchdogSeverity.ERROR
}

For a direct compiler call:

-P plugin:org.jetbrains.kotlinx.library.api.watchdog:diagnosticSeverity=MUTABLE_COLLECTION_PUBLIC_API:error

See also​