“For” hack with Option monad in Java

There has been some discussion going on in the blogosphere about monads, and especially about the Haskell Maybe monad or the Scala option class. Those are ways to prevent problems with NULL and NPEs that Java lacks. Java returns NULL form many methods to indicate failure or no result. Suppose we have a method which returns a name:

The problem with this method is that we don’t know if it returns null. So the developers needs to deal with length == null, though the compiler doesn’t force the developer to deal with the returned NULL. A lazy developer then leads to null pointer exceptions. Other languages deal in different ways with this problem. Groovy has safe operators and Nice has option types.

Some posts like the one from James show how to use options in Java. All have the problem that you need to unwrap the value inside the option / maybe. Scala ans Haskell do that automatically for you, with the case classes in Scala for example.

But there is a construct with syntactic sugar in Java which unwraps the value from inside another class: the for loop from Java 1.5.

To make this work we need our option class to implement Iterable.

And the None and Some sub classes to return an empty iterator

or an iterator with one item.

Then voila Java does the unwrapping for us and instead of

we can write (sacrificing the else):

Thanks for listening.

Update: Completely ignoring the point of this post, Euxx posted a correction for the single element list creation I did.

Happens all the time in IT, people missing the point but nitpicking on something irrelevant. Other than that, if we start arguing performance, “The java.util.Collections class also have number of other utility methods that allow to shorten code like this and help to improve performance of your application.” I’d write (or reuse) a OneElementIterator something like this (could probably be optimized with some further thinking)

(Or again using google collections)

“I can’t not notice the ugly use of ArrayList to create collection with a single element, but what made matter worse, is that author suggested to use 3rd party library to replace those 3 lines of code.”

As far as I know, the JDK does not help you very much with Iterators or Iterables as third party libraries do. So, yes, I’d suggest using a third party library to implement an Iterator/Iterable for Option.