Copy all fields from one record to another.

← Operators and Expressions · Ref: Q1075

Copy with :=: — target gets all field values from source:

  backup <- ServerConfig()
  backup :=: original
  stdout.println(`Backup: ${backup}`)

Source is unchanged. Use 'default operator' to auto-generate :=: from fields.

See Q1058 for copy vs merge vs replace. See Q1076 for partial copies.

Example

defines module qa.operators.copyrecorddata

  defines class

    ServerConfig
      host <- String()
      port <- Integer()
      maxConn <- Integer()

      ServerConfig()
        ->
          host as String
          port as Integer
          maxConn as Integer
        this.host :=: host
        this.port :=: port
        this.maxConn :=: maxConn

      default operator ?
      default operator $
      default operator :=:

  defines program

    CopyRecordDataDemo()
      stdout <- Stdout()

      //Create a fully configured server
      primary <- ServerConfig("db.prod.internal", 5432, 100)
      stdout.println(`Primary: ${primary}`)

      //Copy all fields to a backup config
      backup <- ServerConfig()
      backup :=: primary
      stdout.println(`Backup: ${backup}`)

      //Copy overwrites existing values too
      staging <- ServerConfig("staging.local", 3000, 10)
      stdout.println(`Staging before: ${staging}`)
      staging :=: primary
      stdout.println(`Staging after: ${staging}`)

Common mistakes

E50060 — EK9 records have no clone() method, so primary.clone() is unresolved — use the :=: copy operator to copy all fields. See ek9 -h E50060 for details.

Incorrect:

backup :=: primary.clone()

Correct:

backup :=: primary
Other ways to ask this
  • Transfer field values between two records using :=:
  • Clone a record into a second record in EK9
  • In Java I'd use clone() or a copy constructor. What's the EK9 equivalent?
  • I have two Config records and need to make the second match the first

Coming from another language?

Java: clone() or copy constructor. Python: copy.copy(). Rust: Clone trait. Go: struct assignment. EK9: :=: operator copies all fields from source to target.

Keywords: duplicate, clone, transfer, copy, record, fields, :=: