How do I check if a variable has a value in EK9?

← Operators and Expressions · Ref: Q981

Append ? after the variable name. It returns true if the variable holds a value, false if unset or absent.

SYNTAX: variable?

  if userName?
    stdout.println(userName)
  isReady <- connection? and credentials?
  stdout.println(`Has name: ${userName?}`)

The ? calls _isSet() internally. No parentheses needed — it is a suffix operator like Kotlin's !! but for checking, not forcing.

Example

defines module qa.operators.issetconditions

  defines function

    findDiscount() as pure
      -> loyaltyYears as Integer
      <- rtn as Float: Float()

      premiumThreshold <- 5
      standardThreshold <- 2

      if loyaltyYears > premiumThreshold
        rtn: 0.15
      else if loyaltyYears > standardThreshold
        rtn: 0.05

  defines program

    IsSetConditionsDemo()
      stdout <- Stdout()

      // ? suffix checks if variable is set
      customerName <- "Alice"
      stdout.println(`Has name: ${customerName?}`)

      // ? in if condition
      discount <- findDiscount(3)
      if discount?
        stdout.println(`Discount: ${discount}`)
      else
        stdout.println("No discount available")

      // ? on unset value
      noDiscount <- findDiscount(1)
      if noDiscount?
        stdout.println("Should not reach here")
      else
        stdout.println("No discount for short tenure")

      // ? in compound boolean
      firstName <- "Bob"
      lastName <- String()
      if firstName? and lastName?
        stdout.println("Both names set")
      else
        stdout.println("Not all names set")

Common mistakes

E01073 — 'null' does not exist in EK9. Use the ? suffix to check if a variable is set: 'if discount?' not 'if discount != null'. See ek9 -h E01073.

Incorrect:

      if discount != null
        stdout.println(`Discount: ${$discount}`)

Correct:

      if discount?
        stdout.println(`Discount: ${discount}`)
Other ways to ask this
  • What is the set check operator in EK9?
  • How do I test whether a variable is set before using it?
  • Show me how to use ? to check if something is set in EK9

Coming from another language?

EK9: append ? after any variable to check if it holds a value. Returns Boolean. No parentheses, no method call — just variable? as a suffix.

Keywords: value check, condition, isSet, set check, suffix