Skip to content

Instantly share code, notes, and snippets.

@pcdavid
Created June 3, 2009 07:14
Show Gist options
  • Save pcdavid/122836 to your computer and use it in GitHub Desktop.
Save pcdavid/122836 to your computer and use it in GitHub Desktop.
Optional.java
public class Optional<T> {
private final boolean isSet;
private final T value;
public static <T> Optional<T> nothing() {
return new Optional<T>(false, null);
}
public static <T> Optional<T> value(T value) {
return new Optional<T>(true, value);
}
private Optional(boolean isSet, T value) {
this.isSet = isSet;
this.value = value;
}
public boolean isSet() { return isSet; }
public T getValue() { return value; }
public String toString() {
if (!isSet) {
return "#<nothing>";
} else {
return "#<value: " + String.valueOf(value) + ">";
}
}
public static void main(String[] args) {
System.out.println("Nothing: " + Optional.nothing());
System.out.println("Explicit int: " + Optional.value(42));
System.out.println("Explicit null: " + Optional.value(null));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment