Spread operation
Learn how to expand collections.
The spread operation expands a collection into a sequence of values, often used to combine collections or pass multiple values to a function.
Spreading collections
To combine two collections, place the ... where you want to insert the elements of the second collection:
["a", .../*<list>*/, "z"]
In the above example, the list is expanded between two elements. You could also expand it at the beginning to prepend the elements or at the end to append the elements — it all depends on where you place the ... operator.
When spreading maps, be aware that the keys of the second map take precedence over the keys of the first map. This means that if both maps have the same key, the value from the second map will overwrite the value from the first map. Here is an example to illustrate this:
["a": 1, "b": 2, ...["b": 3, "c": 4]] // ["a": 1, "b": 3, "c": 4]
Spreading arguments
Another use case for spreading is when you need to pass a list of values as arguments to a function.
Consider the following example:
let power = (a, b) => a ** b;let numbers = [2, 3];power(...numbers) // 8
In this example, because the numbers variable is a list, the spread operator maps each element to the corresponding argument based on the order in which they appear in the list.
Because CQL supports named arguments, you can also spread a map of arguments:
let power = (a, b) => a ** b;let numbers = ["b": 3, "a": 2];power(...numbers) // 8
Note that the order of the arguments in the map does not matter because each argument is mapped to the corresponding parameter based on the parameter name.
For collections that mix elements with and without keys, the same rule applies as for named and positional arguments: elements without keys must come first.
let power = (a, b) => a ** b;let numbers = ["b": 3, 2];power(...numbers) // 🚨 Invalid
The above example is invalid and results in an error because the element without a key comes after the element with a key.