Oneofs

Something that's often left unaddressed by statically typed programming languages is the ability to model a value that can take on one of an arbitrary set of types. Many other languages approximate this sort of ability through a notion of "sub-typing" relationships between a hierarchy of types. While sub-typing as found broad use and much support throughout the programming languages ecosystem, Claro has been designed under the belief that sub-typing leaves much to be desired and opens the door to all sorts of unwanted and unnecessary complexity and leads to error-prone coding patterns. So, on principle, Claro will never support sub-typing, and instead provides support for oneof types (also known as tagged-unions in other languages).

Fig 1:


var intOrStr: oneof<int, string>;

Check the Concrete Type of a Oneof With the instanceof Operator

The entire point of a oneof type is to be able to write branching logic on the concrete type that is actually represented by the oneof at runtime. One way of achieving this is with the instanceof boolean operator that allows you to check the concrete type at runtime:

Fig 2:


var intOrStr: oneof<int, string>;

random::forSeed(20000)
  |> random::nextNonNegativeBoundedInt(^, 2)
  |> var r = ^;

match (r) {
  case 0 -> intOrStr = 10;
  case _ -> intOrStr = "ten";
}
print("intOrStr: {intOrStr}");

if (intOrStr instanceof int) {
  print("Found an int!");
} else {
  print("Found a string!");
}

Output:

intOrStr: 10
Found an int!

It's somewhat nonsensical to do an instanceof check on any concrete type so Claro statically rejects that.

Fig 3:


if (10 instanceof int) {
  print("Obviously an int");
}
if (10 instanceof string) {
  print("Obviously not a string");
}

Compilation Errors:

oneofs_EX3_example.claro:1: Illegal instanceof Check: int is a statically known concrete type! Using instanceof over a statically known concrete type is never necessary.
if (10 instanceof int) {
    ^^^^^^^^^^^^^^^^^
oneofs_EX3_example.claro:4: Illegal instanceof Check: int is a statically known concrete type! Using instanceof over a statically known concrete type is never necessary.
if (10 instanceof string) {
    ^^^^^^^^^^^^^^^^^^^^
2 Errors