Null Check On Mutable Property

ID

kotlin.null_check_mutable

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Kotlin

Tags

concurrency, null-safety

Description

Reports if (x != null) guards where x is a var property.

A mutable property can be reassigned to null by another thread — or by a callback invoked within the same thread — between the null-check and the use of the value. Kotlin’s smart-cast intentionally refuses to narrow the type of var properties for this reason.

Rationale

var handler: Runnable? = null

// Bad — handler can become null between check and call
if (handler != null) {
    handler!!.run()   // FLAW — race condition
}

// Good — value captured immutably before use
handler?.let { it.run() }

// Good — local copy
val h = handler
if (h != null) h.run()

Remediation

  • Use ?.let { …​ } to capture the value atomically before the null check.

  • Copy the property to a local val and null-check the local copy.