1 package com.github.davidmoten.util; 2 3 import rx.Observable; 4 5 public class Optional<T> { 6 7 private final T value; 8 private final boolean present; 9 10 private Optional(T value, boolean present) { 11 this.value = value; 12 this.present = present; 13 } 14 15 public boolean isPresent() { 16 return present; 17 } 18 19 public T get() { 20 if (present) 21 return value; 22 else 23 throw new NotPresentException(); 24 } 25 26 public T or(T alternative) { 27 if (present) 28 return value; 29 else 30 return alternative; 31 } 32 33 public Observable<T> toObservable() { 34 if (present) 35 return Observable.just(value); 36 else 37 return Observable.empty(); 38 } 39 40 public static <T> Optional<T> fromNullable(T t) { 41 if (t == null) 42 return Optional.absent(); 43 else 44 return Optional.of(t); 45 } 46 47 public static <T> Optional<T> of(T t) { 48 return new Optional<T>(t, true); 49 } 50 51 public static <T> Optional<T> absent() { 52 return new Optional<T>(null, false); 53 } 54 55 public static class NotPresentException extends RuntimeException { 56 57 private static final long serialVersionUID = -4444814681271790328L; 58 59 } 60 }