Choice Types in Java With FunctionalJ.io

A "Tagged Union" Implementation in Java: Introduction

A choice type allows us to specify, in an ad-hoc fashion, what values can be used (see tagged union). It is similar to enum but it also allows the payload to parameterize its values. With choice types, it is possible and easier to design the data type where invalid values are not representable. This article discusses how FunctionalJ.io's @Choice annotation can be used to create choice types in Java.

Background

In essence, a type is a set of possible values. Boolean means only true or false can be used. Integer means that only a whole number between 2^32 to (-2^32)+1 can be used. Types may have other functions, like describing how to construct the data in memory and what we can do with it, but at the essence, a type defined what values are allowed. In statically-typed compiled languages, this constraint is enforced at the compiled time which, as we all (Java programmers) know, contributes greatly to ensuring the correctness and reliability of the program. It also makes code much more comprehensible.