Unions
Declaring unions
A union value chooses one of several possible types. These are called the case types.
Below, the case types of u are nat and string.
So a u value must be either a nat or a string.
A value of a case type can implicitly convert to the union type.
Short unions can be squeezed onto one line.
Case getters
Declaring the union implicitly creates functions for getting each of its case types.
In this example, those are
nat64 nat64?(a u) and string string?(a u) .
(nat is an alias for nat64, so the case getter function uses the type's true name.)
If a case getter is used as a condition, its argument will implicitly convert to the case type in the scope where the condition is true.
"match" on unions
match works on a union value. This uses the same syntax as a match on an enum value.
If you handle every case, you don't need an else branch.
Methods
A union can list functions that must exist for all case types. These are called methods.
For each case type, there must be a function matching the method,
with the case type injected as the first parameter.
This is called the method implementation.
Above, the method implementations are size nat(a nat) and
size nat(a string) .
The nat implementation is defined in the example;
the string implementation comes from the standard library.
Declaring the method also implicitly creates a caller function
which takes the union type as its first parameter.
Above, the caller is size nat(a u) .
The caller matches on the union and calls the appropriate implementation.
If the union is on one line, omit the do keyword.
Auto functions on unions
Unions support the same auto functions as records.
==returnsfalsefor different case types. For values of the same case type, it calls the==function for that type.<=>works similarly. When the values are of the same case type, it calls<=>for the case type.
When the values are not of the same case type, case types that were declared earlier are considered lesser.
If you declared the union asunion(nat,string),nats are less thanstrings.
If you declared the union asunion(string,nat),strings are less thannats.hashhashes the case type index (abovenatis0andstringis1), then calls thehashfunction for the case type.tojsonreturns a single-key object with the case type name as a key, and calls that type'stojsonfor the value.
Restrictions
Almost any types can be combined in a union, but:
- Multiple aliases to the same type (e.g.
natandnat64) aren't allowed. - Multiple instances of the same generic type aren't allowed. (These will be explained in Type parameters.)
You can work around that by defining wrapper types with unique names.