What are the rules for using 'default operator' in EK9?

← Operators and Expressions · Ref: Q949

default operator rules: can't use in extending classes if parent has it. Property types must support required operators.

1. EXTENDING CLASS RESTRICTION (E07190)

If a parent class already uses 'default operator' for a given operator, the extending class cannot also use 'default operator' for the same operator. Override it explicitly instead.

2. PROPERTY TYPE REQUIREMENTS (E07200)

When you use 'default operator ==', all property types in the class must support ==. If any property's type lacks ==, compilation fails with E07200.

DEFAULT OPERATOR BEHAVIOR

'default operator' generates field-by-field implementations:

  default operator == compares all fields
  default operator $ concatenates field string representations
  default operator ? checks all fields are set

See Q116 for default operator syntax. See Q245 for custom operators.

Example

defines module qa.operators.defaultrules

  defines class

    <?-
      Class using default operators.
      All property types (String, Integer) support ==, $, ?.
    -?>
    Person
      name <- String()
      age <- Integer()

      default private Person() as pure

      Person() as pure
        ->
          name as String
          age as Integer
        this.name :=: name
        this.age :=: age

      //default generates field-by-field comparison
      default operator <=>
      default operator ==
      default operator <>
      default operator $
      default operator #?
      default operator :=:

      override operator ? as pure
        <- rtn as Boolean: name? and age?

  defines program

    DefaultOperatorRulesDemo()
      stdout <- Stdout()

      p1 <- Person("Alice", 30)
      p2 <- Person("Alice", 30)
      p3 <- Person("Bob", 25)

      stdout.println(`p1 == p2: ${p1 == p2}`)
      stdout.println(`p1 == p3: ${p1 == p3}`)
      stdout.println(`p1: ${p1}`)
      stdout.println(`p1 set: ${p1?}`)

Common mistakes

E02030 — The class already has 'default operator <=>' defined. Changing == to <=> creates a duplicate operator definition, triggering E02030. Each operator can only be defined once. See ek9 -h E02030 for details.

Incorrect:

default operator <=>

Correct:

default operator ==
Other ways to ask this
  • What triggers E07190 DEFAULT_OPERATOR_IN_EXTENDING_CLASS?
  • What triggers E07200 PROPERTY_TYPE_MISSING_OPERATOR?
  • Can I use default operator in a class that extends another?
  • Why do my properties need operators for default to work?

Coming from another language?

Java: IDE-generated equals/hashCode. Python: dataclass auto-generates. Rust: derive(Eq, Hash). Kotlin: data class auto-generates. EK9: 'default operator' with compile-time validation that property types support the required operator.

Keywords: property, field, default, extending, operator, E07200, generate, E07190, auto, type