Unions
Tagged unions are the main way to achieve polymorphism in niva
Unions are types that can be represented by one of several options at a time.
Declaration of union is like declaration of type
+ switch
Pattern match
To work with a union, you first need to understand what form it is in.
Switch syntax is used for this.
Exhaustive
If you don't check all form options, this will be a compile time error.
Instantiate
It is impossible to instantiate the root of the union, since then it is not clear what form it will correspond to.
But you can create branches, each root branch is no different from a regular type declaration.
// TODO as note
Note that you don't need the root qualifier like Shape.Rectangle
. This is debatable, but I like the branches to be no different from the declaration of ordinary top-level types
Single line syntax
Fields for Roots
Unlike other ML languages, union roots can contain fields
Both Student
and Teacher
have a name
field here.
This simplifies 2 things at once:
There is no need to repeat common fields for each union's branch.
You don't need to pattern match the Person to gain access to the
name
field
Include one union into another
// TODO tree picture
// TODO replace with car models
So now u can pattern match it like
Or on more general Sas
You will get a compilation error if you inadvertently check out more general branches before more specific ones
// TODO error text