Last active
December 20, 2015 09:49
-
-
Save Fristi/6110963 to your computer and use it in GitHub Desktop.
Optional types in Java, Haskell and F#
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
data Maybe a = Just a | Nothing |
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
type 'a Option = None | Some of 'a |
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
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