Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Heterogeneous collections

A heterogeneous collection holds values of different kinds. Plenty still gives it one element type: an enum or an anonymous sum describes the alternatives. The possible types are known at compile time.

Use the classes and enums you have defined to choose a representation:

CollectionRepresenting different kinds of data
ListsUse an enum wrapper for a named interface, or `list[A
SetsUse an enum or anonymous sum whose alternatives are supported keys.
DictionariesUse enums or anonymous sums for mixed keys, values, or both.

An anonymous sum, written A | B, holds one value of either type. It is not a set collection: set[T] holds distinct values. An enum gives its alternatives names and can define methods; an anonymous sum needs a match to use each member’s own interface.

These techniques do not create an open-ended collection accepting any type. Adding a new kind means extending the enum or sum and handling it wherever matching must be exhaustive. Protocols constrain generic calls; they are not runtime element types such as list[MyProtocol].