Skip to content

Instantly share code, notes, and snippets.

@watsoncj
Created December 27, 2011 20:32
Show Gist options
  • Save watsoncj/1525043 to your computer and use it in GitHub Desktop.
Save watsoncj/1525043 to your computer and use it in GitHub Desktop.
Option pattern from FP for Java Developers
public final class Some<T> extends Option<T> {
private final T value;
public Some(T value) {
this.value = value;
}
public boolean hasValue() {
return true;
}
public T get() { return value; }
@Override
public String toString() { return "Some("+value+")"; }
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != Some.class)
return false;
Some<?> that = (Some<?>) other; Object thatValue = that.get(); return value.equals(thatValue);
}
@Override
public int hashCode() {
return 37 * value.hashCode();
}
}
public final class None<T> extends Option<T> {
public static class NoneHasNoValue extends RuntimeException {}

public None() {}
public boolean hasValue() { return false; }
public T get() { throw new NoneHasNoValue(); }
@Override
public String toString() { return "None"; }
@Override
public boolean equals(Object other) {
return (other == null || other.getClass() != None.class) ? false : true;
}
@Override
public int hashCode() { return -1; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment