the blog for developers

“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:

String name = getName("hello");
int length = name.length();

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.

Option[String] option = getName("hello");

for (String name: option) {
	// do something with name
}

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

public abstract class Option[T] implements Iterable[T] {
}

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

public abstract class None[T] extends Option[T] {
  public Itertator[T] iterator() { return EMPTY_ITERATOR; }
}

or an iterator with one item.

public abstract class Some[T] extends Option[T] {
  public Itertator[T] iterator() { 
    // or better use google-collections
    List[T] list = new ArrayList[T]();
    list.add(this.value);
    return list.iterator();
}

Then voila Java does the unwrapping for us and instead of

Option[String] option = getName("hello");
if (option instance of Some) {
    String name = ((Some) option).value();
} else { ... }

we can write (sacrificing the else):

for (String name: getName("hello")) {
	// do something with name
}

Thanks for listening.

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

  return Collections.singletonList(this.value).iterator();

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)

public class OneElementIterator[T] implements Iterator[T] {

	private boolean done = false;
	private T element;
	
	public OneElementIterator(T element) {
		this.element = element;
	}
	public boolean hasNext() {
		return ! done;
	}
	public T next() {
		done = true;
		return element;
	}
	public void remove() {
		// not supported, throw exception;
	}
}

(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.

About the author

stephan Stephan Schmidt has been working with internet technologies for the last 20 years. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own. You can find him on Google +

Discuss on Hacker News Vote on HN