Copy a child class including parent fields.

← Operators and Expressions · Ref: Q1080

Copy an inherited type with :=: — parent and child fields included:

  dst :=: src

Both parent and child must declare 'default operator :=:'. The parent must be declared 'as open' to allow extension.

See Q1075 for basic copy.

Example

defines module qa.operators.copywithinheritance

  defines class

    Vehicle as open
      make <- String()
      year <- Integer()

      Vehicle()
        ->
          make as String
          year as Integer
        this.make :=: make
        this.year :=: year

      default operator ?
      default operator $
      default operator :=:

    Car extends Vehicle
      doors <- Integer()

      Car()
        ->
          make as String
          year as Integer
          doors as Integer
        super(make, year)
        this.doors :=: doors

      default operator ?
      default operator $
      default operator :=:

  defines program

    CopyWithInheritanceDemo()
      stdout <- Stdout()

      //Source has parent fields (make, year) and child field (doors)
      src <- Car("Toyota", 2024, 4)
      stdout.println(`Source: ${src}`)

      //Copy transfers all fields including inherited ones
      dst <- Car()
      dst :=: src
      stdout.println(`Copy: ${dst}`)
      stdout.println(`Copy set?: ${dst?}`)

Common mistakes

E05030 — The parent class must be declared 'as open' to allow extension — EK9 types are closed by default. See ek9 -h E05030 for details.

Incorrect:

    Vehicle

Correct:

    Vehicle as open
Other ways to ask this
  • I have a Car that extends Vehicle and need to copy all fields including make and year
  • In Java I'd call super.clone() in a subclass. Write the EK9 equivalent
  • Given a class hierarchy with Vehicle and Car, duplicate a Car preserving parent fields
  • Transfer all data from one extended object to another using :=:

Coming from another language?

Java: clone() with super.clone(). Python: copy.deepcopy() handles inheritance. Go: embed + struct copy. EK9: default operator :=: on both parent and child handles the chain automatically.

Keywords: child, inheritance, :=:, parent, super, copy, extends