Guard a comparison result when one sensor reading might be unset.

← Operators and Expressions · Ref: Q1084

Guard a comparison result when an operand might be unset:

  cmp <- active <=> offline
  if cmp?
    stdout.println($cmp)

When either operand is unset, <=> produces an unset result. Always guard with ? before using the value.

See Q1082 for normal comparison. See Q1087 for checking if records are set.

Example

defines module qa.operators.compareunsetrecords

  defines class

    Sensor
      name <- String()
      reading <- Float()

      Sensor()
        ->
          name as String
          reading as Float
        this.name :=: name
        this.reading :=: reading

      default operator

  defines program

    CompareUnsetRecordsDemo()
      stdout <- Stdout()

      active <- Sensor("Temperature", 23.5)
      offline <- Sensor()
      stdout.println(`Active: ${active}`)
      stdout.println(`Offline set?: ${offline?}`)

      //Compare set with unset — result is unset
      cmp <- active <=> offline
      if cmp?
        stdout.println(`Comparison: ${cmp}`)
      else
        stdout.println("Comparison unset: cannot compare with unset sensor")

Common mistakes

E07540 — A <=> comparison can be unset, so branch on the guarded result `if cmp?` (a Boolean); branching on the raw Integer `if cmp` is not Boolean-compatible and triggers E07540. See ek9 -h E07540 for details.

Incorrect:

      if cmp

Correct:

      if cmp?
Other ways to ask this
  • I have two sensor objects and one might be uninitialised — compare them safely
  • In Java this would throw NullPointerException. Write the safe EK9 comparison
  • Given an active and an offline sensor, compare them and handle the unset case
  • Check whether a <=> comparison result is valid before using it

Coming from another language?

Java: NullPointerException if null. Python: TypeError on None comparison. Go: panic on nil. EK9: comparison with unset object returns unset result — no crash, no wrong answer.

Keywords: compare, <=>, unset, absent, check result, tri-state, guard