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.

ZERO IS A VALUE

':=?' assigns only when the variable is unset. A port of 0 is set, so it is kept - unlike 'port or 8080' in Python or 'if port == 0' in Go, which replace a valid 0.

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 assign-if-unset — 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 assign-if-unset 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
  • Apply a default port number only when the config port is unset.
  • How do I conditionally assign an Integer only when the variable is unset?
  • A server config has an optional port — apply the default 8080 if not configured.
  • In Java I'd check if port == null before assigning a default. What does EK9 use?
  • Migrating from Go where I check if port == 0 — what is the EK9 pattern for default integers?

Coming from another language?

Ruby: port ||= 8080. Kotlin: port = port ?: 8080. JavaScript: port ??= 8080. EK9: port :=? 8080.

Keywords: guarded, fallback, default, conditional, server, :=?, port, assignment, config, integer