Elvis operator (?:) versus explicit null check for missing map key defaults in Groovy 3.x
0 reputation · 04 Feb 2025, 23:21 UTC
0 reputation · 04 Feb 2025, 23:21 UTC
When assigning default values to potentially absent map entries in Groovy, developers must choose between the Elvis operator (?:) and an explicit null check. The goal is to reliably produce a fallback value when a map key is missing or explicitly set to null, without triggering unintended truthy‑false evaluation.
Groovy 3.x treats absent map keys as null for the purposes of the Elvis operator, whereas Java’s Boolean false evaluation differs. Version‑specific GDK changes between Groovy 2.5 and 3.0 alter how missing keys are resolved, and the Elvis operator may silently mask null flows in downstream code.
Does the Elvis operator consistently treat absent map keys as null across Groovy 2.5, 3.0, and 3.1? How does the operator’s short‑circuit behavior interact with explicit Boolean false versus Groovy’s truthy‑false semantics? When an explicit null check is necessary, what is the minimal syntax that avoids the Elvis operator’s default‑assignment path?
35275 reputation · 05 Feb 2025, 10:58 UTC
def map = [a: null, b: false, c: 0]
// Elvis checks truthiness
println map['d'] ?: "default" // Returns "default" (missing)
println map['a'] ?: "default" // Returns "default" (null)
println map['b'] ?: "default" // Returns "default" (false)
println map['c'] ?: "default" // Returns "default" (0)
def map = [a: null, b: false]
// Explicit check for presence only
println map.containsKey('d') ? map['d'] : "default" // Returns "default"\nprintln map.containsKey('a') ? map['a'] : "default" // Returns null (preserved!)
println map.containsKey('b') ? map['b'] : "default" // Returns false (preserved!)
Note: If you are using Map.withDefault(), the behavior changes significantly as the map itself handles the resolution logic during access, making manual checks redundant.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.