Compare two Product records by price.

← Operators and Expressions · Ref: Q1082

Compare two records with <=> and use the derived operators:

  cmp <- itemA <=> itemB
  if itemA > itemB
    stdout.println("A is greater")

'default operator' generates <=> and all derived comparison operators (==, <>, <, >, <=, >=).

See Q1085 for sorting records. See Q1083 for equality checking.

Example

defines module qa.operators.comparetworecords

  defines class

    Product
      name <- String()
      price <- Float()

      Product()
        ->
          name as String
          price as Float
        this.name :=: name
        this.price :=: price

      default operator

  defines program

    CompareRecordsDemo()
      stdout <- Stdout()

      itemA <- Product("Keyboard", 49.99)
      itemB <- Product("Mouse", 29.99)

      cmp <- itemA <=> itemB
      stdout.println(`Compare: ${cmp}`)

      if itemA > itemB
        stdout.println(`${itemA} costs more`)
      else
        stdout.println(`${itemB} costs more`)

      if itemA == itemB
        stdout.println("Same product")
      else
        stdout.println("Different products")

Common mistakes

E50060 — EK9 has no .compareTo() method; use the '<=>' operator for three-way comparison. See ek9 -h E50060 for details.

Incorrect:

cmp <- itemA.compareTo(itemB)

Correct:

cmp <- itemA <=> itemB
Other ways to ask this
  • Write code that checks which of two records is greater
  • Determine ordering between two objects using <=>
  • In Java I'd use Comparable.compareTo(). What is the EK9 equivalent?
  • I have two products and need to know which one costs more

Coming from another language?

Java: implements Comparable<T>, compareTo(). Python: __lt__, __eq__ or functools.total_ordering. Rust: impl Ord. Go: manual comparison. EK9: default operator <=> or custom operator <=>.

Keywords: compare, ordering, comparison, <=>, less, record, greater