Apply a default Configuration record only if no configuration was provided.

← Operators and Expressions · Ref: Q1232

The :=? guarded assignment operator works on ANY type, not just primitives. It assigns the value only if the target variable is currently unset.

  config <- Configuration()
  defaultConfig <- Configuration("localhost", 8080)
  config :=? defaultConfig

If config is unset, it receives the default. If config already has a value, the assignment is skipped. This is an ASSIGNMENT operator.

See Q1220 for :=? on strings.

Example

defines module qa.operators.guardassign.record

  defines record

    Configuration
      host as String: String()
      port as Integer: 0

      Configuration()
        ->
          host as String
          port as Integer
        this.host: host
        this.port: port

      default operator

  defines function

    loadSavedConfig()
      <- rtn <- Configuration()
      //Simulates: no saved configuration found

    loadEnvironmentConfig()
      <- rtn <- Configuration("env-host", 9090)

  defines program

    GuardAssignRecordDemo()
      stdout <- Stdout()

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

      config <- Configuration()
      defaultPort <- 8080
      defaultConfig <- Configuration("localhost", defaultPort)
      config :=? defaultConfig
      stdout.println(`Config: ${config}`)

      // === RECORD IS ALREADY SET — :=? is skipped ===

      existingConfig <- Configuration("production.example.com", 443)
      existingConfig :=? defaultConfig
      stdout.println(`Existing preserved: ${existingConfig}`)

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

      appConfig <- Configuration()
      appConfig :=? loadSavedConfig()
      appConfig :=? loadEnvironmentConfig()
      fallbackPort <- 3000
      appConfig :=? Configuration("fallback-host", fallbackPort)
      stdout.println(`App config: ${appConfig}`)

Common mistakes

E01073 — EK9 has no null. Use :=? to conditionally assign when a variable is unset. This works on records, classes, and all types. See ek9 -h E01072 for details.

Incorrect:

      if config == null
        config := defaultConfig

Correct:

      config :=? defaultConfig
Other ways to ask this
  • How do I use :=? guarded assignment with a record type?
  • Given an optional Configuration record, apply defaults if it is unset.
  • In Java I'd check if config == null before setting defaults. What does EK9 offer?
  • Migrating from Kotlin where I use config ?: defaultConfig — what is the EK9 equivalent?

Coming from another language?

Java: if (config == null) config = defaultConfig. Python: config = config or defaultConfig. Kotlin: config = config ?: defaultConfig. EK9: config :=? defaultConfig — one operator, works on any type.

Keywords: user-defined, configuration, guarded, record, default, assignment, :=?, unset