Do the ?? and ?: operators check for null in EK9?

← Operators and Expressions · Ref: Q1059

No. EK9 has no null. The ?? and ?: operators check whether a value is SET, not whether it is null.

?? VALUE COALESCING:

  result <- name ?? "default"

Returns name if name is SET. Returns "default" if name is UNSET.

?: ELVIS COALESCING:

  result <- name ?: "default"

Same behaviour as ?? — returns left if SET, otherwise right.

The distinction from other languages:

  Java: name != null ? name : "default"     checks null
  Kotlin: name ?: "default"                  checks null
  EK9: name ?? "default"                     checks isSet

In EK9, a variable can exist but be UNSET. This is not the same as null. An unset String is a String object that has no meaningful value yet. It still exists — you can call ? on it to check.

  name <- String()     name exists, but is UNSET
  name?                returns false (unset)
  name := "Alice"     now SET
  name?                returns true

If BOTH sides of ?? are unset, the result is unset.

See Q899 for all coalescing operators. See Q898 for ? is not ternary. See Q883 for tri-state semantics.

Example

defines module qa.operators.coalescingisset

  defines program

    CoalescingDemo()
      stdout <- Stdout()

      //Unset string
      name <- String()
      stdout.println(`name is set: ${name?}`)

      //?? returns right when left is unset
      greeting <- name ?? "stranger"
      stdout.println(`Hello ${greeting}`)

      //Set the name
      name := "Alice"
      stdout.println(`name is set: ${name?}`)

      //?? now returns left (it is set)
      greeting := name ?? "stranger"
      stdout.println(`Hello ${greeting}`)

      //?: works the same way
      title <- String()
      displayTitle <- title ?: "Untitled"
      stdout.println(`Title: ${displayTitle}`)

Common mistakes

E01073 — 'null' does not exist in EK9 — a variable is either set or unset (tri-state), so assign a real value rather than 'null'. See ek9 -h E01073 for details.

Incorrect:

      name := null

Correct:

      name := "Alice"
Other ways to ask this
  • Is ?? a null coalescing operator in EK9?
  • How do ?? and ?: work — are they null checks?
  • What do the coalescing operators actually check in EK9?

Coming from another language?

Java: ternary with null check. Kotlin: ?: (elvis) checks null. JavaScript: ?? (nullish coalescing). EK9: ?? and ?: check isSet, not null — EK9 has no null.

Keywords: operator, unset, elvis, isset, null, coalescing