Unions and Enums
Use unions for explicit states, and enums for simple named constants.
Variants
A union lists the possible shapes a value can have.
union Download:
Queued
Running(Int)
Variants With Data
A variant can carry data, such as Running(Int).
status: Download = Running(40)
Enums
An enum is for variants with no payload. It is still useful when a value should be one of a closed set of labels: the compiler rejects unknown labels, match expressions can be exhaustive, and adding a label points you to the code that must handle it.
enum Direction:
North
South
Explicit States
Modeling states as variants prevents impossible combinations of fields.
state: Download = Failed("network")
Example
download.brp
union Download:
Queued
Running(Int)
Done(String)
Failed(String)
pure func describe(download: Download) -> String:
match download:
Queued: "queued"
Running(percent): "running " + percent.to_string()
Done(path): "done: " + path
Failed(msg): "failed: " + msg
func main(args: List[String]) -> Void:
print(describe(Running(40))) -- prints: running 40
Try it
terminal
blorp run download.brp