Created
February 14, 2012 21:54
-
-
Save jonseymour/1830835 to your computer and use it in GitHub Desktop.
Option<T>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Iterator; | |
import java.util.NoSuchElementException; | |
/** | |
* Implements support for an option type. | |
* <pre> | |
* // assuming Option<T> foo() | |
* | |
* for (T t : foo()) { | |
* doSomething(t); | |
* return; | |
* } | |
* doDefaultThing(); | |
* </pre> | |
* | |
* @author jseymour | |
* @inspiredBy http://eng.wealthfront.com/2010/05/better-option-for-java.html | |
* @param <T> | |
*/ | |
public abstract class Option<T> | |
implements Iterable<T>, Cloneable | |
{ | |
private static class Impl<T> extends Option<T> implements Iterator<T> { | |
enum State { | |
INIT, | |
ITERATOR, | |
HAS_NEXT, | |
NEXT | |
} | |
private final T value; | |
private State state = State.INIT; | |
public Impl(T value) { | |
this.value = value; | |
} | |
public boolean hasNext() { | |
switch (state) { | |
case HAS_NEXT: | |
case ITERATOR: | |
state = State.HAS_NEXT; | |
return value != null; | |
default: | |
return false; | |
} | |
} | |
public T next() { | |
if (state != State.HAS_NEXT || value == null) { | |
throw new NoSuchElementException("illegal state: attempt to use option with checking for existence first"); | |
} | |
state = State.NEXT; | |
return value; | |
} | |
public void remove() { | |
throw new UnsupportedOperationException(); | |
} | |
public Iterator<T> iterator() { | |
state = State.ITERATOR; | |
return this; | |
} | |
public Option<T> clone() | |
{ | |
return new Impl<T>(value); | |
} | |
} | |
public static <T> Option<T> some(T value) | |
{ | |
return new Impl<T>(value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment