union¶
ALFA supports both ‘tagged’ and ‘non-tagged’ forms of union.
Tagged Union¶
A union
is similar to a record
, however only 1 field is permitted have a value assigned at any one time.
ALFA unions are tagged unions with a field name and datatype.
Unions can include assert to perform validation.
union Delivery {
Post : PostalRequest
Courier : CourierRequest
EMail : string
Message : InstantMessage
HandDelivered : void
}
In the example above, the void type is required even if the field is merely tagged. Simply having HandDelivered
( without a datatype ) indicates the field is declared in a shared fields {}
block.
ALFA unions are tagged unions, therefore entries can share the same datatype. E.g.
union Distance {
Miles : int
Km : int
}
When a union includes
a trait, the fields of the trait conform to the behaviour
of a union, i.e. only a single field can be assigned on the union at any one time.
trait Menu {
Starters : list< Starter >
Mains : list< Main >
Desserts : list< Dessert >
}
record CustomerOrder includes Menu {
TableNumber : int
Waiter : string
}
// There will be offers on one of the categories in the Menu
union SpecialOffer includes Menu {
}
Non-tagged Union¶
Non-tagged union lists a set of data types, and the singular value of the union should be of one of those types. A type cannot be repeated.
In the declaration below, the value of Numeric
will be one of the 3 types specified.
union Numeric = int | long | double