View Javadoc
1   package com.github.davidmoten.guavamini;
2   
3   public final class Optional<T> {
4   
5       private final T value;
6       private final boolean present;
7   
8       private Optional(T value, boolean present) {
9           this.value = value;
10          this.present = present;
11      }
12  
13      private Optional() {
14          //no-arg constructor to enable kryo (a bit yukky but not a big deal)
15          this(null, false);
16      }
17  
18      public boolean isPresent() {
19          return present;
20      }
21  
22      public T get() {
23          if (present)
24              return value;
25          else
26              throw new NotPresentException();
27      }
28  
29      public T or(T alternative) {
30          if (present)
31              return value;
32          else
33              return alternative;
34      }
35  
36      public static <T> Optional<T> fromNullable(T t) {
37          if (t == null)
38              return Optional.absent();
39          else
40              return Optional.of(t);
41      }
42  
43      public static <T> Optional<T> of(T t) {
44          return new Optional<T>(t, true);
45      }
46  
47      public static <T> Optional<T> absent() {
48          return new Optional<T>();
49      }
50  
51      public static class NotPresentException extends RuntimeException {
52  
53          private static final long serialVersionUID = -4444814681271790328L;
54  
55      }
56  
57      @Override
58      public String toString() {
59          return present ? String.format("Optional.of(%s)", value) : "Optional.absent";
60      }
61  }