Optional: Java's Optional in Generic Code

Keep Java's own Optional, with an Effect Path and the same instances as Maybe.

Optional at a glance

ModelsA value, or empty, in Java's own type
ReplacesNothing: it is Java's own type
Effect PathOptionalPath
InstancesFunctor, Applicative, Selective, Monad, MonadError<Unit>, Alternative, MonadZero, Foldable, Traverse
Choose it whenA method you call already returns an Optional; otherwise Maybe, or compare every type in Choosing a Type

What You'll Learn

  • Read a record's Optional fields with a fallback, through an OptionalPath
  • Pass an Optional to code written once for any container, through its MonadError instance
  • Say what widening an Optional costs, and why Maybe pays nothing
  • Choose between Optional and Maybe, and convert between them

See Example Code

The code on this page is OptionalBook.java: the page includes it, so the build compiles and runs it. OptionalBookTest.java holds what the page says each method does.


Java's own type

java.util.Optional is everywhere: repositories return it, configuration lookups return it, and records hold it in fields that may be empty. Higher-Kinded-J does not replace it. It gives Optional an Effect Path, OptionalPath, for application code, and a MonadError instance, so that a method written once for any container accepts an Optional too. Maybe is the library's own type for the same job.

The code on this page uses these imports, with CustomerProfile and EmailAddress from the order records the Optics chapter introduces:

import java.util.Optional;
import org.higherkindedj.example.book.optics.cast.CustomerProfile;
import org.higherkindedj.example.book.optics.cast.EmailAddress;
import org.higherkindedj.hkt.effect.OptionalPath;
import org.higherkindedj.hkt.effect.Path;

Optional fields on an OptionalPath

A CustomerProfile holds a nickname and a second email address, altEmail, each as an Optional. Path.optional takes one, map changes the value when there is one, and getOrElse reads it with a fallback:

  // nickname is an Optional field, as many records' optional fields are
  static String greeting(CustomerProfile profile) {
    return Path.optional(profile.nickname())
        .map(nickname -> "Hello, " + nickname)
        .getOrElse("Hello, " + profile.name());
  }

  static OptionalPath<String> secondAddress(CustomerProfile profile) {
    return Path.optional(profile.altEmail()).map(EmailAddress::value);
  }

ADA has the nickname "Countess" and no second address, and CHARLES has a second address and no nickname:

    String forAda = greeting(ADA);
    String forCharles = greeting(CHARLES);

    OptionalPath<String> charlesAddress = secondAddress(CHARLES);
    // OptionalPath(charles@example.org)
    Optional<String> adaAddress = secondAddress(ADA).run();
    // Optional.empty

forAda is "Hello, Countess", and forCharles is "Hello, Charles". Optional's own map and orElse do as much for one field. The Path pays off when via chains it into another Path, or toEitherPath gives the absence a reason. run() gives the Optional back, and toMaybePath() turns the Path into a MaybePath.

Methods

Optional's own methods are the JDK's. The library adds these:

MethodWhat it does
Path.optional(optional), Path.present(a), Path.absent()Build an OptionalPath
map(f), via(f), filter(p)Change the value, chain a step, or keep the value only if it passes; a map function that returns null gives an empty Path
getOrElse(a), orElsePath(a)Read the value with a fallback, or keep the Path, filling an empty one with the fallback
run(), isPresent(), isEmpty()Give the Optional back, or say which case it holds
toMaybePath(), toEitherPath(error)Convert to a MaybePath, or to an EitherPath whose error says why
Maybe.fromOptional(optional), maybe.toOptional()Convert between Optional and Maybe
OPTIONAL.widen(optional), OPTIONAL.narrow(kind)Move an Optional in and out of Kind

Working with Kind

Generic code, written once for any container, takes Optional through its MonadError instance, as MonadError shows. Its error type is Unit: an empty Optional is the error, and it carries no detail. Maybe's instance has the same shape, so one method serves both. These are the extra imports for writing the method and calling it:

import static org.higherkindedj.hkt.instances.Witnesses.maybe;
import static org.higherkindedj.hkt.instances.Witnesses.optional;
import static org.higherkindedj.hkt.maybe.MaybeKindHelper.MAYBE;
import static org.higherkindedj.hkt.optional.OptionalKindHelper.OPTIONAL;

import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.MonadError;
import org.higherkindedj.hkt.TypeArity;
import org.higherkindedj.hkt.Unit;
import org.higherkindedj.hkt.WitnessArity;
import org.higherkindedj.hkt.instances.Instances;
import org.higherkindedj.hkt.maybe.Maybe;
import org.higherkindedj.hkt.maybe.MaybeKind;
import org.higherkindedj.hkt.optional.OptionalKind;

F stands for any container, and its WitnessArity bound says the container holds one type:

  // Written once, for any container whose error is absence
  static <F extends WitnessArity<TypeArity.Unary>> Kind<F, String> contact(
      MonadError<F, Unit> absence, Kind<F, EmailAddress> email, String fallback) {
    return absence.handleError(absence.map(EmailAddress::value, email), unit -> fallback);
  }

    MonadError<OptionalKind.Witness, Unit> optionals = Instances.monadError(optional());
    MonadError<MaybeKind.Witness, Unit> maybes = Instances.monadError(maybe());

    Optional<String> fromOptional =
        OPTIONAL.narrow(contact(optionals, OPTIONAL.widen(CHARLES.altEmail()), "no address"));
    // Optional[charles@example.org]
    Maybe<String> fromMaybe =
        MAYBE.narrow(
            contact(maybes, MAYBE.widen(Maybe.fromOptional(ADA.altEmail())), "no address"));
    // Just(no address)

Optional is a JDK class, so it cannot implement OptionalKind. OPTIONAL.widen wraps it in a small holder object each time, and narrow unwraps it, where widening a Maybe allocates nothing. The instance's of(null) gives an empty Optional, and so does a map whose function returns null, as Optional.map does. Optional has instances of other type classes too, such as Selective and Traverse, each an object of its own, and Optional at a glance, at the head of the page, lists them.

Should you use Optional or Maybe?

Both model a value that may be missing, treat null alike, and have the same instances. They differ in who owns the type, and so in what widening costs:

You needUse
To work with APIs and records that already use OptionalOptional, with OptionalPath or its instance
A value that may be missing, in code you controlMaybe: it is its own Kind, so widening allocates nothing, and toEither gives its absence a reason
Generic code that must accept an Optional from callersOptional's instance, widening with OPTIONAL.widen
To move between the twoMaybe.fromOptional(optional) and maybe.toOptional()
A missing value that must say whyEither, through toEitherPath(error)

Previous: Maybe Next: IO