Last-element macro

Learn how to get the last element of a collection.

This macro gets the last element of a collection.

To determine the last element, this macro uses the order of the collection and not the key or index of the element.

Note that trying to get the last 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.

Croct's mascot neutral
Why not return null instead?

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:

last of /*<collection>*/
Try in Playground

You can also prefix the macro with a definite article for readability:

the last of /*<collection>*/
Try in Playground

Parameters

These are the supported parameters:

collection

A non-empty collection from which you want to get the last element.

Examples

Here is an example of how to get the last element of a list:

last of [1, 2, 3] // 3
Try in Playground

You can also get the last element of a map:

last of ["a": 1, "b": 2, "c": 3] // 3
Try in Playground

To get the last key of a map, you can use the keys macro:

last of keys of ["a": 1, "b": 2, "c": 3] // "c"
Try in Playground