The Option/Maybe and Either types

As hinted before, our solution is to use a return type that contains the wanted value or something else in case of error. Those kinds of data structures are called union types. A union can contain values of different types, but only one at a time.

Let's start with the easiest of both union types we will see in this chapter. As always, naming is a difficult thing in computer science and people came up with different names to designate mostly the same structure:

  • Haskell calls it the Maybe type, as does Idris
  • Scala calls it the Option type, as does OCaml, Rust, and ML
  • Since version 8, Java has an Optional type, as does Swift and the next specification of C++

Personally, I prefer the denomination Maybe as I consider an ...

Get Functional PHP now with O’Reilly online learning.

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