First-element macro
Learn how to get the first element of a collection.
This macro gets the first element of a collection.
To determine the first element, this macro uses the order of the collection and not the key or index of the element.
Note that trying to get the first element of an empty collection results in an error, so be sure to provide a default value in cases where the collection might be empty.
An error helps distinguish between empty collections and those with null elements, so you can easily handle both cases.
Syntax
This macro has the following syntax:
first of /*<collection>*/
You can also prefix the macro with a definite article for readability:
the first of /*<collection>*/
Parameters
These are the supported parameters:
- collection
A non-empty collection from which you want to get the first element.
Examples
Here is an example of how to get the first element of a list:
first of [1, 2, 3] // 1
You can also get the first element of a map:
first of ["a": 1, "b": 2, "c": 3] // 1
To get the first key of a map, you can use the keys macro:
first of keys of ["a": 1, "b": 2, "c": 3] // "a"
If the collection might be empty and you want to return null instead of an error, you can use a fallback operator:
first of /*<collection>*/ or else null