Generate all operators with default, but customise the string representation.

← Operators and Expressions · Ref: Q1098

Override before default:

  override operator $ as pure
    <- rtn as String: `Custom(age=${age})`
  default operator

Overrides go BEFORE 'default operator', which must be last in the class body. See Q1069 for mixing default with overrides, Q1097 for default operator basics.

Example

#!ek9
defines module qa.operators.overrideafterdefault

  defines class

    Base as open
      name as String: String()

      Base()
        -> name as String
        this.name := name

      default operator

    Child extends Base
      age as Integer: Integer()

      Child()
        ->
          childName as String
          age as Integer
        super(childName)
        this.age :=? age

      //Custom $ BEFORE default operator
      override operator $ as pure
        <- rtn as String: `Child(age=${age})`

      default operator

  defines program

    OverrideAfterDefaultDemo()
      stdout <- Stdout()

      base <- Base("ParentObj")
      stdout.println($base)

      child <- Child("ChildObj", 10)
      stdout.println($child)

Common mistakes

E01086 — default operator must be LAST. Put override operators BEFORE it.

Incorrect:

      default operator
      override operator $ as pure
        <- rtn as String: `Custom`

Correct:

      override operator $ as pure
        <- rtn as String: `Child(age=${age})`
Other ways to ask this
  • I want default operator for everything except $ which I need to customise
  • In Java I'd auto-generate equals/hashCode but override toString(). Write the EK9 way
  • Given a child class, override the parent's default $ with a custom format
  • Use default operator for most operators but provide a custom override operator $

Coming from another language?

Java: Lombok @Data + manual toString(). Kotlin: data class + override fun toString(). EK9: override operator $ before default operator.

Keywords: $, combine, customise, default operator, override, string