Collections in validation script

About collections in validation script

A collection is a list of data. Usually you create it when retrieving attributes or relations. You can refer to a specific element in the collection in multiple ways.

Note If a reference points to a value that doesn't exist, the rule will crash. For example, retrieving the fifth value of a list that only contains four values causes a crash.

Reference Result
mylist.first() The first value in the list mylist.
mylist.last() The last value from the list mylist.
mylist[1] The second element from the list mylist. The number is the index of the value you want to retrieve from the list.

Note The first element has index zero. As a consequence, mylist.first() is equivalent to mylist.[0].

mylist.get(1) The second element from the list my list. It is very similar to the example above.
mylist?.get(1) The second element from the list. However, this syntax is null-safe. ?. is the null-safe getter of Groovy. You cannot combine the ?. with the [ ... ] notation. This means that if the referenced attribute is not present, the result is null, whereas the expression without the question mark fails to execute.

Using the *. operator in collections

When using relations, you sometimes only need to have one value of the target assets, such as the name. You can use the *. operator for this.

Script Purpose
isIn ('expectedTargetName', relations['Is Related To']*.name) Check whether expectedTargetName is in the list of all names of the target assets. The *. operator applies the .name on every target asset and creates a new list.
isEvery (relations['Is Related To']*.name, {targetName -> startsWith (targetName, 'S')}) This will check that every target asset related to the current asset has a name that starts with S.

Validate the first element of a collection

In many situations, the first element is the only element you actually want to validate. For example, if you want to check if the first Description attribute is equal to a certain value, you can do this:

Script Purpose
isEqual (attributes['Description'].first(), 'myvalue') Retrieve the first element from list of Descriptions and compare this to myvalue.
isEqual (attributes['Description'], ['myvalue']) Check wether the list of Descriptions is equal to the given list ['myvalue']. This is identical to the first example, but has as a side effect that if there is more than one occurrence of the Description attribute, the comparison will return false. As a consequence, it validates that there is exactly one Description attribute.