Create a Product class with full operator support in one line.
← Operators and Expressions · Ref: Q1097
One line generates all operators:
default operator
Must be the last item in the class body. Generates ==, <>, <, >, <=, >=, <=>, $, $$, #?, :=:, :~:, :^:, ? from declared fields. See Q949 for default operator rules, Q1098 for overriding individual operators after default.
Example
defines module qa.operators.definerecorddefaultops defines class Product name <- String() price <- Float() Product() -> name as String price as Float this.name :=: name this.price :=: price //One line generates all operators default operator defines program DefineRecordDefaultOpsDemo() stdout <- Stdout() a <- Product("Widget", 9.99) b <- Product("Widget", 9.99) c <- Product("Gadget", 29.99) //$ string stdout.println(`Product: ${a}`) //== equality if a == b stdout.println("a and b are equal") //<=> comparison if a < c stdout.println("Widget is cheaper than Gadget") //:=: copy backup <- Product() backup :=: a stdout.println(`Backup: ${backup}`) //#? hashcode stdout.println(`Hash: ${#?a}`)
Common mistakes
E01086 — 'default operator' must be the LAST item in a class body — no methods or fields may follow it. See ek9 -h E01086 for details.
Incorrect:
default operator someMethod() as pure <- rtn as String: "oops"
Correct:
default operator
Other ways to ask this
- I need a class with copy, compare, equals, string, hash — generate them all automatically
- In Kotlin I'd use a data class. Write the EK9 equivalent with default operator
- Given a class with name and price fields, add all operators without writing each one
- Set up a complete class with 'default operator' to generate everything
Coming from another language?
Kotlin: data class Product(val name: String, val price: Float). Java: record Product(String name, float price). EK9: class with 'default operator' as last line.
Keywords: one line, all, automatic, operators, generate, default operator