Merge two lists together using :~: operator.

← Operators and Expressions · Ref: Q1081

Merge one list into another with :~::

  team :~: newHires

All elements from the source are added to the end of the target. The source is unchanged.

See Q1058 for copy vs merge vs replace.

Example

#!ek9
defines module qa.operators.mergecollection

  defines program

    MergeCollectionDemo()
      stdout <- Stdout()

      //Two separate lists of names
      team <- ["Alice", "Bob", "Charlie"]
      newHires <- ["Diana", "Eve"]
      stdout.println(`Team: ${team}`)
      stdout.println(`New hires: ${newHires}`)

      //Merge new hires into the team list
      team :~: newHires
      stdout.println(`After merge: ${team}`)

      //Merge a single element
      team :~: "Frank"
      stdout.println(`After single merge: ${team}`)

Common mistakes

E50060 — EK9's List has no addAll method — use the merge operator ':~:' to add all elements of one list into another. See ek9 -h E50060 for details.

Incorrect:

team.addAll(newHires)

Correct:

team :~: newHires
Other ways to ask this
  • Add all elements from one list into another list
  • Combine two lists in place using :~:
  • In Java I'd use addAll(). What is the EK9 equivalent?
  • I have two lists and need to merge the second into the first

Coming from another language?

Java: list.addAll(other). Python: list.extend(other). Go: append(slice, other...). EK9: list :~: otherList or list += otherList.

Keywords: :~:, addAll, append, collection, combine, list, merge