Chapter 7. More Advanced Features of Opa

Before we dive into developing Birdy, you need to learn few more things about Opa. In this chapter, we will discuss more complex types, which will help you deal with more complex data that you will encounter in this part of the book.

Learning More About Types

You learned about primitive values (int, float, string) in Primitive Values and about records in Records. Now it is time to extend your type arsenal.

Variant Types

Variant types, as the name suggests, allow you to express values that can take several different variants. Probably the simplest such type is a boolean value, which is defined in Opa as follows:

type bool = {false} or {true}

The variants are separated with the or keyword and the variants themselves are just regular record types. Lack of a type for a given field implies it is of type void (which we covered in Event Handlers), so the preceding code can also be written as follows:

type bool = {void false} or {void true}

Such void-typed fields make little sense in regular records, as the field value carries no information. However, in variant types they make perfect sense, as their presence is important and differentiates between variants.

In this simple form, with all variants having just one field of type void, those types correspond to enumeration types, as you may know from other programming languages. Here is another example from the standard Opa library:

type Date.weekday = {monday} or {tuesday} or {wednesday} or {thursday}
  or {

Get Opa: Up and Running now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.