How do I provide a default value when something might be unset in EK9?
← Control Flow · Ref: Q985
EK9 provides two operators for default values:
?? VALUE COALESCING
Returns the left value if SET, otherwise the right:
displayName <- userName ?? "Guest" timeout <- configuredTimeout ?? defaultTimeout
:=? GUARDED ASSIGNMENT
Only assigns if the target is currently UNSET:
serverHost <- String() serverHost :=? "localhost" serverHost :=? "other" has no effect — already set to localhost
WHEN TO USE EACH
?? when creating a new variable with a fallback.
:=? when conditionally initialising an existing variable.
COMBINING WITH GUARDS
if connection <- tryConnect(primaryHost) useConnection(connection) else fallbackHost <- primaryHost ?? backupHost if backup <- tryConnect(fallbackHost) useConnection(backup)
Example
defines module qa.controlflow.defaultvalue defines function lookupSetting() as pure -> settingName as String <- rtn as String: String() if settingName == "host" rtn: "production.example.com" defines program DefaultValueDemo() stdout <- Stdout() // ?? for inline defaults configuredHost <- lookupSetting("host") activeHost <- configuredHost ?? "localhost" stdout.println(`Host: ${activeHost}`) // ?? when lookup returns unset missingPort <- lookupSetting("port") activePort <- missingPort ?? "8080" stdout.println(`Port: ${activePort}`) // :=? for conditional initialisation logLevel <- String() logLevel :=? "INFO" stdout.println(`Log level: ${logLevel}`) // :=? has no effect when already set logLevel :=? "DEBUG" stdout.println(`Still: ${logLevel}`)
Common mistakes
E01010 — 'null' does not exist in EK9 and the ? symbol is the isSet suffix, not a conditional. Use ?? for value coalescing: left ?? right returns left if set, else right.
Incorrect:
activeHost <- configuredHost != null ? configuredHost : "localhost"
Correct:
activeHost <- configuredHost ?? "localhost"
E01010 — The ? is the isSet suffix, not part of a conditional expression. Use :=? for guarded assignment — it only assigns if the target is currently unset.
Incorrect:
logLevel <- logLevel ? logLevel : "INFO"
Correct:
logLevel :=? "INFO"
Other ways to ask this
- How do I fall back to a default in EK9?
- What is the EK9 equivalent of a default value expression?
- How does ?? work for defaults in EK9?
- How do I use :=? for conditional initialisation?
Coming from another language?
EK9 uses ?? for value coalescing and :=? for guarded assignment. Both handle unset values without any concept of null.
Keywords: fallback, coalescing, guarded, unset, default