Apply a default port number only when the config port is unset.

← Control Flow · Ref: Q1221

The :=? guarded assignment operator assigns a value ONLY if the target variable is currently unset. If the variable already has a value, the assignment is skipped.

  port <- Integer()
  defaultPort <- 8080
  port :=? defaultPort
  //port is now 8080 because it was unset

This is an ASSIGNMENT operator — it sets a variable.

See Q1038 for :=? with config fallback chains.

Example

defines module qa.flow.guardassign.integer

  defines function

    loadPortFromEnvironment()
      <- rtn <- Integer()
      //Simulates: no port configured in environment

    loadPortFromConfigFile()
      <- rtn <- 9090

  defines program

    GuardAssignIntegerDemo()
      stdout <- Stdout()

      // === PORT IS UNSET — :=? assigns the default ===

      port <- Integer()
      defaultPort <- 8080
      port :=? defaultPort
      stdout.println(`Server port: ${port}`)

      // === PORT IS ALREADY CONFIGURED — :=? is skipped ===

      customPort <- loadPortFromConfigFile()
      customPort :=? defaultPort
      stdout.println(`Custom port preserved: ${customPort}`)

      // === FALLBACK CHAIN — first set value wins ===

      serverPort <- Integer()
      serverPort :=? loadPortFromEnvironment()
      serverPort :=? loadPortFromConfigFile()
      fallbackPort <- 8080
      serverPort :=? fallbackPort
      stdout.println(`Resolved port: ${serverPort}`)

Common mistakes

E01073 — EK9 has no null. Use :=? to conditionally assign — it only sets the value when the variable is currently unset. See ek9 -h E01072 for details.

Incorrect:

      if port == null
        port := defaultPort

Correct:

      port :=? defaultPort
Other ways to ask this
  • 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?

Java: if (port == null) port = 8080. Python: port = port or 8080 (but fails for port 0). Go: if port == 0 { port = 8080 } (but 0 might be valid). Kotlin: port = port ?: 8080. EK9: port :=? defaultPort — correct tri-state semantics, 0 is a valid set value.

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