How do ? and guard expressions work together in EK9?

← Operators and Expressions · Ref: Q982

The ? suffix checks if a value is set. Guards declare AND check in one step.

USE ? when you already have the variable:

  if temperature?
    stdout.println(`Temp: ${$temperature}`)

USE GUARD when you need to declare and check:

  if temperature <- readSensor()
    stdout.println(`Temp: ${$temperature}`)

The guard 'if v <- expr()' is equivalent to:

  v <- expr()
  if v?
    use v

But the guard is a single atomic operation — v only exists inside the block.

COMBINE THEM when you need both:

  if reading <- readSensor() then reading > minimumThreshold
    process(reading)

Example

defines module qa.operators.issetwithguard

  defines function

    lookupPrice() as pure
      -> productCode as String
      <- rtn as Float: Float()

      if productCode == "WIDGET"
        rtn: 29.99
      else if productCode == "GADGET"
        rtn: 49.99

  defines program

    IsSetWithGuardDemo()
      stdout <- Stdout()

      widgetCode <- "WIDGET"
      gadgetCode <- "GADGET"
      mysteryCode <- "MYSTERY"

      // ? suffix on variable that might be unset
      maybePrice <- lookupPrice(widgetCode)
      if maybePrice?
        stdout.println(`Found price: ${maybePrice}`)

      // Guard declares + checks in one step (equivalent but more concise)
      if gadgetPrice <- lookupPrice(gadgetCode)
        stdout.println(`Gadget: ${gadgetPrice}`)

      // Guard with unset result — block skipped
      if unknownPrice <- lookupPrice(mysteryCode)
        stdout.println("Should not print")
      else
        stdout.println("Product not found")

      // ? on unset — no guard needed since variable exists
      emptyPrice <- Float()
      if emptyPrice?
        stdout.println("Should not print")
      else
        stdout.println("Price is unset")

Common mistakes

E01073 — 'null' does not exist in EK9. Use a guard 'if v <- expr()' to declare and check in one step. See ek9 -h E01073.

Incorrect:

      gadgetPrice <- lookupPrice(gadgetCode)
      if gadgetPrice != null
        stdout.println(`Gadget: ${$gadgetPrice}`)

Correct:

      if gadgetPrice <- lookupPrice(gadgetCode)
        stdout.println(`Gadget: ${gadgetPrice}`)
Other ways to ask this
  • What is the relationship between ? suffix and if v <- expr guard?
  • When do I use ? vs a guard in EK9?
  • Show me ? and guards used together in EK9 code

Coming from another language?

EK9 has two patterns: variable? checks an existing variable, 'if v <- expr()' guard declares and checks in one step. Use ? when you already have the variable, guards when declaring.

Keywords: guard, isSet, combine, declaration guard, suffix