-
Notifications
You must be signed in to change notification settings - Fork 4
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
Optionalclass that also supports null as a value. - NotNull: Another replacement for Java's
Optionalclass and ensures it never contains null. - Result: Similar to
Maybebut 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.
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
Serializableso you can use it as a field inSerializableobjects. - 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 equivalentNotNullobject. -
nullToEmpty()method returns an emptyMaybeif its value is null.
Maybe has three static factory methods:
-
Maybe.empty()returns an emptyMaybe. All emptyMaybevalues share a single common instance to reduce memory footprint. -
Maybe.of(value)returns a fullMaybe. The resultingMaybeis always full even ifvalueisnull. -
Maybe.cast(class, value)returns aMayberepresenting an attempt to cast thevalueto an instance of the given class. An emptyMaybeis returned if thevaluecannot be cast into the given class safely. Anullvalue will result in a fullMaybe.
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 emptyNotNull. All emptyNotNullvalues share a single common instance to reduce memory footprint. -
NotNull.of(value)returns a fullNotNullifvalueis not null. Otherwise it returns an emptyNotNull. -
NotNull.cast(class, value)returns aNotNullrepresenting an attempt to cast thevalueto an instance of the given class. An emptyNotNullis returned if thevaluecannot be cast into the given class safely. Anullvalue will also result in an emptyNotNull.