Skip to content

Functional Tropes

Brian Burton edited this page May 21, 2023 · 3 revisions

Functional Tropes

Javimmutable is not a functional programming library but its collections fit naturally into that style of programming. To further support that style the library provides some monadic classes:

  • Maybe: A replacement for Java's Optional class that also supports null as a value.
  • NotNull: Another replacement for Java's Optional class and ensures it never contains null.
  • Result: Similar to Maybe but can contain either a value or an exception.
  • Computation: A deferred computation class that allows a computation to be composed in steps and evaluated later.

Maybe

Collections have a find() method that returns a Maybe rather than a value. The Maybe either contains a value or is empty. Methods are provided to map the value to make new Maybes as well as to safely extract the value or an alternative.

While Maybe is similar to Optional it has a number of advantages:

  • It's Serializable so you can use it as a field in Serializable objects.
  • It doesn't mind storing null so it won't turn itself into an empty if you map its value to null.
  • It has more options for mapping the value.

Though Maybe is fine with storing null it does provide two ways to eliminate null values.

  • notNull() method returns an equivalent NotNull object.
  • nullToEmpty() method returns an empty Maybe if its value is null.

Maybe has three static factory methods:

  • Maybe.empty() returns an empty Maybe. All empty Maybe values share a single common instance to reduce memory footprint.
  • Maybe.of(value) returns a full Maybe. The resulting Maybe is always full even if value is null.
  • Maybe.cast(class, value) returns a Maybe representing an attempt to cast the value to an instance of the given class. An empty Maybe is returned if the value cannot be cast into the given class safely. A null value will result in a full Maybe.

NotNull

Sometimes you really don't want null as a value. In that case NotNull has you covered. It always ensures that null values are mapped to empty NotNulls. If you construct an instance using null as its value you'll get an empty NotNull. Likewise if any map or flatMap function produces a null value the result will be an empty NotNull.

You can convert a NotNull into an equivalent Maybe by calling the maybe() method.

NotNull has three static factory methods:

  • NotNull.empty() returns an empty NotNull. All empty NotNull values share a single common instance to reduce memory footprint.
  • NotNull.of(value) returns a full NotNull if value is not null. Otherwise it returns an empty NotNull.
  • NotNull.cast(class, value) returns a NotNull representing an attempt to cast the value to an instance of the given class. An empty NotNull is returned if the value cannot be cast into the given class safely. A null value will also result in an empty NotNull.

Clone this wiki locally