summaryrefslogtreecommitdiffstats
path: root/example.java
blob: f3d8858ae013c582670455aa6edab549ce976f44 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.Optional;

class Example {
  public static void main(String[] args) {
    /* should print Hi */
    Optional<String> a = Optional.of("Hi");
    System.out.println(StOptional.reduce(a));

    /* should print null */
    Optional<String> b = Optional.empty();
    System.out.println(StOptional.reduce(b));

    /* should print null */
    Optional<String> c = null;
    System.out.println(StOptional.reduce(c));
  }
}

/**
 * Stop Optionals from being used!
 * safely reducing optionals back to their original types.
 */
final class StOptional {
  /**
   * Reduce any optional down to it's original type
   *
   * @param o Optional<?> to reduce
   * @return <?> value of optional
   */
  public static final <T> T reduce(Optional<T> o) {
    return nullish(o) ? null : o.get();
  }

  /**
   * Checks if Optional<?> is null or empty
   *
   * @param o Optional<?>
   * @return boolean true if null or empty, false otherwise
   */
  public static final boolean nullish(Optional<?> o) {
    if (o == null || o.isEmpty())
      return true;
    return false;
  }
}