Skip to content
Kavachकवच

Unions: Matching a union

● Intermediate3 min

match on a union takes each variant apart, and the compiler checks that none is forgotten.

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
union.kav: Kavach code, then what running it prints

Add a variant later, and every match that doesn't handle it becomes an error that names it:

type Status = Pending | Paid | Refunded

fn label(s: Status) -> String {
    match s {
        Status.Pending => "waiting"
        Status.Paid => "done"
    }
}

The compiler refused the program:

kavach run exhaustive.kav

error: this `match` does not cover `Status.Refunded`
exhaustive.kav: Kavach code, then what running it prints