Collection literal

Learn how to represent lists, sets, and maps.

Collection literals use a unified syntax lists, sets, maps, and more.

They are represented as ordered maps, where each element has a key. If no key is provided, the collection acts as a list, using numeric indexes.

Let's look at each of these collection types in more detail.

Lists

A list is a collection of ordered elements that do not require explicit keys. Instead, the keys are automatically generated as sequential numeric indices, starting from zero.

To define a list, enclose the items in square brackets separated by a comma:

let list = [1, 2, 3, 4];
Try in Playground

The above example creates a list with four elements. You can access the elements by their index using the square bracket notation:

list[0] // 1
Try in Playground

Note that the index starts from zero and the elements are listed in the order in which they were defined. So, the first element has an index of 0, the second element has an index of 1, and so on.

Sets

A set is a collection of unique elements. In other words, each item in a set appears only once, meaning no duplicates exist.

Even though CQL has no specific syntax for sets, any collection without duplicates can be considered a set. Therefore, you can use lists to represent sets as well.

For example, although the following variable is technically a list, it can also be considered a set of emojis since each emoji appears only once:

let set = ['👻', '🎃', '👽'];
Try in Playground

You can also use the without duplicates modifier to turn any collection into a set:

let list = ['a', 'b', 'c', 'b'];
list without duplicates // ['a', 'b', 'c']
Try in Playground

This modifier removes duplicate elements in a collection, leaving only the first occurrence of each element.

Maps

A map is a collection where each element has an explicit key that you can use to access it. You can think of an ordered map as a key-value store, where each key is associated with a value.

To create a map, simply enclose the key-value pairs in square brackets. Use a comma to separate each pair and a colon to separate the key and value:

let map = ["yes": "👍", "no": "👎"];
Try in Playground

In a map, keys can be either strings or integers. You can also use variables or expressions as keys:

let three = 3;
[1: "a", "2": "b", three: "c", (3 + 1): "d"]
Try in Playground

Notice that string keys representing integer values are automatically converted to integers. Also, when using variables or expressions as keys, any non-string value is converted to a string.

You can access the elements of a map using the square bracket notation:

map["yes"] // 👍
Try in Playground

An important thing to remember is that maps are arranged in the same order as you define their elements. This is especially relevant when using order-dependent expressions, like ordinal accessors.