Unions
Also known as: union enum enumeration variant tagged union sum type algebraic data type discriminated
● Intermediate5 minBefore this: Records, MatchSpec 2.6
A union is a value that is exactly one of several cases: a Shape is a Circle or a Rect.
type Shape = Circle(radius: Float) | Rect(width: Float, height: Float)
fn area(s: Shape) -> Float {
match s {
Shape.Circle(radius) => 3.14 * radius * radius
Shape.Rect(width, height) => width * height
}
}
fn main() {
print(area(Shape.Circle(radius: 2.0)))
print(area(Shape.Rect(width: 3.0, height: 4.0)))
}The program ran and printed:
kavach run union.kav
12.5612.0
Each case, a variant, can carry its own fields. A match handles each variant, and must handle them all.
Enums
A union whose variants carry nothing is an enum. It can list its variants, name them, and read them back from text:
type Status = Pending | Paid | Refunded
type Code = Ok = 200 | NotFound = 404 | Failed = 500
fn main() {
for s in Status.all() {
print(s.name())
}
const chosen = Status.parse("Paid") ?? Status.Pending
print(chosen)
print(Code.NotFound.value())
print(Code.from(500) ?? Code.Ok)
}The program ran and printed:
kavach run enum.kav
PendingPaidRefundedPaid404Failed
Other languages call these enums, tagged unions, sum types or variants.