Map Not-Null Assertion
ID |
kotlin.map_not_null_assertion |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Kotlin |
Tags |
collections, null-safety |
Description
Reports index access expressions immediately followed by !!.
map[key] returns null when the key is absent, and map[key]!! then throws a
NullPointerException — a less informative exception than the NoSuchElementException
that map.getValue(key) would throw.
Rationale
val name = users[id]!! // FLAW — NPE if id not in map
val name = users.getValue(id) // OK — NoSuchElementException, descriptive
val name = users[id] ?: "unknown" // OK — null-safe fallback
val name = users[id]?.uppercase() // OK — safe call
Remediation
-
Use
map.getValue(key)when the key must be present (throwsNoSuchElementException). -
Use
map[key] ?: defaultwhen a fallback is acceptable. -
Use
map[key]?.let { … }to act only when the key is present.