Skip to content

Instantly share code, notes, and snippets.

@patrickhammond
Created February 27, 2015 16:08
Show Gist options
  • Save patrickhammond/687c6a3597f49d487a77 to your computer and use it in GitHub Desktop.
Save patrickhammond/687c6a3597f49d487a77 to your computer and use it in GitHub Desktop.
Optional implementation pillaged from Java 8 for when you don't have Java 8 APIs available. Optionally (ha!), you could take a look at Guava's Optional (http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Optional.html)
/**
* In the absence of Java 8, here is our Optional duplicated code. Other than the package name,
* this should be a subset of this API, http://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
*/
public final class Optional<T> {
public static <T> Optional<T> of(T value) {
if (value == null) {
return Optional.empty();
}
return new Optional<T>(value);
}
public static <T> Optional<T> empty() {
return new Optional<T>(null);
}
private final T value;
private Optional(T value) {
this.value = value;
}
public boolean isPresent() {
return value != null;
}
public T get() {
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment