Compare two Product records by price.
← Operators and Expressions · Ref: Q1082
To compare two records by PRICE, compare the price fields - a record's fields are public:
byPrice <- itemA.price <=> itemB.price if itemA.price > itemB.price stdout.println(`${itemA.name} costs more`)
'default operator' also gives the whole record <=> and every comparison derived from it (==, <>, <, <=, >, >=), but that ordering compares the fields in declaration order - name first - so itemA <=> itemB is a NAME comparison here (Keyboard before Mouse gives -2), not a price comparison. Use the whole-record operators when that natural ordering is what you want; compare the field (or write a comparator function and use 'sort by') when you want a different key.
See Q1085 for sorting records. See Q1083 for equality checking.
Example
defines module qa.operators.comparetworecords defines record Product name as String: String() price as Float: 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) //Compare by price: a record's fields are public, so compare them directly byPrice <- itemA.price <=> itemB.price stdout.println(`Price compare: ${byPrice}`) if itemA.price > itemB.price stdout.println(`${itemA.name} costs more`) else stdout.println(`${itemB.name} costs more`) //The whole-record <=> from 'default operator' compares the fields in //declaration order - name first - so it is NOT a price comparison byRecord <- itemA <=> itemB stdout.println(`Record compare: ${byRecord}`) sameProduct <- itemA == itemB stdout.println(`Same product: ${sameProduct}`)
Common mistakes
E50060 — EK9 has no .compareTo() method; use the '<=>' operator for three-way comparison. See ek9 -h E50060 for details.
Incorrect:
byRecord <- itemA.compareTo(itemB)
Correct:
byRecord <- 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(), or Comparator.comparing(Product::price). Python: __lt__, __eq__ or functools.total_ordering; key=lambda p: p.price. Rust: impl Ord. Go: manual comparison. EK9: 'default operator' gives a field-order <=> (and the comparisons derived from it); compare a field directly, or write your own operator <=>, for another ordering.
Keywords: less, <=>, comparison, ordering, compare, greater, record