Skip to content

Instantly share code, notes, and snippets.

@Fristi
Last active December 20, 2015 09:49
Show Gist options
  • Save Fristi/6110963 to your computer and use it in GitHub Desktop.
Save Fristi/6110963 to your computer and use it in GitHub Desktop.
Optional types in Java, Haskell and F#
data Maybe a = Just a | Nothing
type 'a Option = None | Some of 'a
public abstract class Option<T> {
public static <E> Option<E> lift(E value) {
if (value == null) {
return new None<E>();
}
return new Some<E>(value);
}
public abstract boolean isEmpty();
public abstract T getValue();
public T getOrElse(T defaultValue) {
return !isEmpty() ? getValue() : defaultValue;
}
}
public final class Some<T> extends Option<T> {
private T value;
public Some(T value) {
if (value == null) {
throw new IllegalArgumentException("Some cannot be null");
}
this.value = value;
}
public Some() {
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public T getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Some some = (Some) o;
return value.equals(some.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
}
public final class None<T> extends Option<T> {
public None() {
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public T getValue() {
throw new NullPointerException("There is no value!");
}
@Override
public boolean equals(Object obj) {
return obj != null && obj instanceof None;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment