Set a default port only if one has not already been provided.
← Control Flow · Ref: Q1152
Only assigns if the target is currently UNSET:
port :=? 8080
If port is already SET, the assignment is skipped. No if-check needed. See Q1038, Q1091.
Example
defines module qa.controlflow.guardedassignment defines program GuardedAssignmentDemo() stdout <- Stdout() //Port is unset — :=? assigns the default port <- Integer() port :=? 8080 stdout.println(`Port: ${port}`) //Port is already set — :=? is skipped port :=? 9090 stdout.println(`Still: ${port}`)
Common mistakes
E01073 — EK9 has no null. Use :=? for conditional assignment — it only sets the value if the target is currently unset.
Incorrect:
if port == null port = 8080
Correct:
port :=? 8080
Other ways to ask this
- I need to assign a fallback value but only when the variable is unset
- In Ruby I'd use ||=. Write the EK9 guarded assignment equivalent
- Given an optional port configuration, apply a default if nothing was set
- Use :=? to conditionally initialise a variable that might already have a value
Coming from another language?
Ruby: port ||= 8080. Kotlin: port = port ?: 8080. JavaScript: port ??= 8080. EK9: port :=? 8080.
Keywords: assignment, fallback, :=?, default, guarded, conditional