Why must methods come before operators in an EK9 class?

← Syntax and Structure Rules · Ref: Q725

EK9 enforces strict ordering within class bodies. Fields come first, then methods, then operators. Once operator declarations begin, no more methods or fields can follow. Violating this triggers E01086.

REQUIRED ORDER

1. Fields (properties) first
2. Constructors and methods second
3. Operators third (including 'default operator')

WHY ENFORCED

Strict ordering makes classes consistently readable. Every EK9 class has the same structure: data at the top, behaviour in the middle, operators at the bottom. This eliminates the need to scan an entire class to find where operators or methods are declared.

DEFAULT OPERATOR

The 'default operator' keyword generates standard operators (==, <>, <=>, $, #?, ?) based on fields. It must appear in the operators section, which is always last.

See Q93 for class definition basics. See Q96 for operator details. See Q238 for the fixed operator set.

Example

defines module qa.syntaxrules.classbodyorder

  defines class

    <?-
      Correct ordering: fields, then methods, then operators.
    -?>
    Product
      name <- String()
      price <- Float()

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

      describe()
        <- rtn as String: `${name} at ${price}`

      applyDiscount()
        -> percent as Float
        factor <- 1.0 - (percent / 100.0)
        price: price * factor

      //Operators must be last
      default operator

  defines program

    ClassBodyOrderDemo()
      stdout <- Stdout()

      item <- Product("Widget", 29.99)
      stdout.println(item.describe())

      item.applyDiscount(10.0)
      stdout.println(item.describe())

      same <- Product("Widget", 29.99)
      stdout.println(`Equal: ${item == same}`)

Common mistakes

E50060 — String has no toUpperCase() method in EK9. Use upperCase() instead. See ek9 -h E50060 for details.

Incorrect:

stdout.println(item.describe().toUpperCase())

Correct:

stdout.println(item.describe())
Other ways to ask this
  • What is E01086 method after operator declaration?
  • What order do fields methods and operators go in EK9?
  • Why did my class fail with a method after default operator?

Coming from another language?

Java: Members can appear in any order within a class. Python: Methods and special methods can be interspersed. Rust: impl blocks are separate from struct definition. Go: Methods are defined outside struct. Kotlin: Members can be in any order. EK9: Strict ordering enforced by grammar: fields then methods then operators.

Keywords: class, ordering, field, method, default, E01086, syntax, operator, structure, body