Write a custom override operator ? for a class with validation logic.

← Operators and Expressions · Ref: Q1089

Override ? before default operator to require all fields:

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

The override keyword is mandatory — every class inherits ? from its base type. 'default operator' must be the LAST item in the class body.

See Q1069 for mixing default with overrides. See Q1070 for which operators need override.

Example

defines module qa.operators.overrideoperatorisset

  defines class

    Registration
      name <- String()
      email <- String()
      age <- Integer()

      Registration()
        ->
          name as String
          email as String
          age as Integer
        this.name :=: name
        this.email :=: email
        this.age :=: age

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

      //Custom ?: require ALL fields before default operator
      override operator ? as pure
        <- rtn as Boolean: name? and email? and age?

      default operator

  defines program

    OverrideOperatorIsSetDemo()
      stdout <- Stdout()

      //Fully set — override ? returns true
      complete <- Registration("Bob", "bob@example.com", 30)
      stdout.println(`Complete set?: ${complete?}`)

      //Partially set — override ? returns false (not all fields set)
      partial <- Registration("Alice")
      stdout.println(`Partial set?: ${partial?}`)
Other ways to ask this
  • I need my Registration to be considered valid only when name, email, and age are all present
  • In Java I'd write a custom isValid() method. Write the EK9 equivalent with override operator ?
  • Given a class with three required fields, make operator ? enforce all-field checking
  • Implement an override operator ? that requires ALL fields to be set before the object is usable

Coming from another language?

Java: custom isValid() method. Python: __bool__ override. Rust: custom is_valid(). EK9: override operator ? before default operator.

Keywords: operator, custom, validate, override, all fields, isSet, ?