the
For any type T,
the(collection: List<T>) : T?
the(collection: Bag<T>) : T?
Extracts the unique element from a collection, if it has a unique element and returns null otherwise.
Examples
Basic uses
singleItem = the([42]); // Returns 42, since the collection has a unique item
empty = the(fromTo(1, 0)); // Returns null, since the collection is empty
multiple = the([1, 2, 3]); // Returns null, since the collection has multiple items
Finding a Unique Device
// Returns the device if exactly one match exists, null otherwise
coreRouter = the(
foreach device in network.devices
where device.name == "core-router-1"
select device
);
Use Cases
- Extracting a unique result from a filtered collection
- Validating uniqueness constraints
- Safely accessing "the one" element when you expect exactly one
Notes
-
theis particularly useful when combined withisPresentto distinguish between "no results" and "too many results" -
Prefer
theover manual checks likelength(collection) == 1for cleaner, more idiomatic code.That is, replace
if length(myIntegers) == 1 then max(myIntegers) else null:Integerwith justthe(myIntegers).
See Also
Guides
- Collections - Comprehensive guide on Lists, Bags, and ordering
- Missing Values - Working with null values