import java.util.NoSuchElementException; public class Optional { private static final Optional EMPTY = new Optional(Null.INSTANCE); private T value; protected Optional(T value){ this.value = value; } public static Optional of(T value){ return new Optional(value); } @SuppressWarnings("unchecked") public static Optional empty(){ return (Optional) EMPTY; } public static Optional ofNullable(T value){ if(value == null){ return empty(); }else{ return of(value); } } public boolean isPresent(){ return !(this.value == null || this == EMPTY); } public T get() throws NoSuchElementException { if(isPresent()){ return value; }else{ throw new NoSuchElementException(); } } public T orElse(T other) { if(isPresent()){ return value; }else{ return other; } } private static class Null { private static final Null INSTANCE = new Null(); private Null(){ // Private constructor super(); } } }