Provide a fallback display name when the user name is unset.
← Operators and Expressions · Ref: Q1091
Elvis coalescing:
displayName <- userName ?: "Guest"
Returns left if set, right otherwise. ?: and ?? are synonyms. See Q899 for all coalescing operators, Q1092 for coalescing min/max.
Example
defines module qa.operators.elviscoalescing defines program ElvisCoalescingDemo() stdout <- Stdout() //User name is unset — fallback to "Guest" userName <- String() displayName <- userName ?: "Guest" stdout.println(`Display: ${displayName}`) //User name is set — use the actual value knownUser <- "Alice" displayName2 <- knownUser ?: "Guest" stdout.println(`Display: ${displayName2}`)
Common mistakes
E01073 — EK9 has no null; use tri-state (unset/set) values with the ?: coalescing operator for a fallback. See ek9 -h E01073 for details.
Incorrect:
displayName <- userName ?: null
Correct:
displayName <- userName ?: "Guest"
Other ways to ask this
- I have an optional user name and need to show 'Guest' if it is missing
- In Kotlin I'd use the ?: elvis operator. Write the EK9 equivalent
- Given a possibly-unset string, return it if set or a default otherwise
- Supply a default value for an unset variable using ?: coalescing
Coming from another language?
Kotlin: value ?: default. JavaScript: value ?? default. Swift: value ?? default. C#: value ?? default. EK9: value ?: default or value ?? default.
Keywords: elvis, coalescing, default, ??, unset, fallback, ?: