Google’s Guava open source library provides a class Optional<T> that holds zero or one value, as a superior alternative to null references. Its a certainly good idea, but also a very mature, well understood idea. Haskell has Maybe, Scala has Option.
For some inexplicable reason, Guava’s designer turn there back on prior art and wisdom with a lame dismissal: Optional is not intended as a direct analogue of any existing “option” or “maybe” construct from other programming environments, though it may bear some similarities.
“Some similarities”? Sure does! Its the same damn abstraction. How many abstractions can you get that consist of exactly 0..1 values of some type T? One, that’s how many.
And one of the most useful capabilities of this abstraction is that can be a monad; essentially, support a flatMap (of flattenTransform in Guava terms) operation. The flattening part is useful when you have an Optional<T> value, and a function from T to another Optional<S> value. If you simply transform the input, you get a Optional<Optional<T>> container as a result. Typically, you want to flatten any number of Optional wrappers down into a single Optional<S> layer. That is, either I have a result value of type S, or I don’t.
Sadly, Guava hobbled their Optional class by leaving out a flatten operation.
I find myself speculating on why they left it out, and suspect that it resulted from the kind of ignorance of the outside world that seems to common in Java programming culture. An attitude that its OK to reinvent a existing abstraction that has been widely used and well understood, and yet ignore or dismiss any wisdom that comes from outside the Java ecosystem.
quelgar said,
June 7, 2012 at 8:55 am
I wrote the most recent comment on that page, attempting to show why flatMap is important. They have a ticket for it, which they closed for the usual silly reasons. I initially liked Guava, but then I realized that none of their APIs offer flatMap.
fsarradin said,
July 27, 2012 at 2:57 pm
Note that flatMap in Guava terms is transformAndConcat ( http://docs.guava-libraries.googlecode.com/git-history/v13.0/javadoc/com/google/common/collect/FluentIterable.html#transformAndConcat(com.google.common.base.Function) ). As you can guess here, in Guava 13, you have a monadic operation for Iterables but still not for Optional. And Optional is not even an Iterable, even if it is a container! So the only ways to get flatMap for Optional is by: 1/ reimplementing Optional 2/ adding flatMap as static method with two parameters (can be really ugly) 3/ using to level of Optional (https://gist.github.com/3184604) 4/ giving up and use null checking (not a real solution) 5/ using Scala
Jed Wesley-Smith said,
August 20, 2012 at 11:11 am
We wrote our own extension library with proper Option and Either types: https://bitbucket.org/atlassian/fugue/overview