1 /*
2  * Copyright (C) 2011 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package org.whispersystems.libsignal.util.guava;
18 
19 import static org.whispersystems.libsignal.util.guava.Preconditions.checkNotNull;
20 
21 import java.io.Serializable;
22 import java.util.Iterator;
23 import java.util.Set;
24 
25 
26 /**
27  * An immutable object that may contain a non-null reference to another object. Each
28  * instance of this type either contains a non-null reference, or contains nothing (in
29  * which case we say that the reference is "absent"); it is never said to "contain {@code
30  * null}".
31  *
32  * <p>A non-null {@code Optional<T>} reference can be used as a replacement for a nullable
33  * {@code T} reference. It allows you to represent "a {@code T} that must be present" and
34  * a "a {@code T} that might be absent" as two distinct types in your program, which can
35  * aid clarity.
36  *
37  * <p>Some uses of this class include
38  *
39  * <ul>
40  * <li>As a method return type, as an alternative to returning {@code null} to indicate
41  *     that no value was available
42  * <li>To distinguish between "unknown" (for example, not present in a map) and "known to
43  *     have no value" (present in the map, with value {@code Optional.absent()})
44  * <li>To wrap nullable references for storage in a collection that does not support
45  *     {@code null} (though there are
46  *     <a href="http://code.google.com/p/guava-libraries/wiki/LivingWithNullHostileCollections">
47  *     several other approaches to this</a> that should be considered first)
48  * </ul>
49  *
50  * <p>A common alternative to using this class is to find or create a suitable
51  * <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">null object</a> for the
52  * type in question.
53  *
54  * <p>This class is not intended as a direct analogue of any existing "option" or "maybe"
55  * construct from other programming environments, though it may bear some similarities.
56  *
57  * <p>See the Guava User Guide article on <a
58  * href="http://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained#Optional">
59  * using {@code Optional}</a>.
60  *
61  * @param <T> the type of instance that can be contained. {@code Optional} is naturally
62  *     covariant on this type, so it is safe to cast an {@code Optional<T>} to {@code
63  *     Optional<S>} for any supertype {@code S} of {@code T}.
64  * @author Kurt Alfred Kluever
65  * @author Kevin Bourrillion
66  * @since 10.0
67  */
68 public abstract class Optional<T> implements Serializable {
69   /**
70    * Returns an {@code Optional} instance with no contained reference.
71    */
72   @SuppressWarnings("unchecked")
absent()73   public static <T> Optional<T> absent() {
74     return (Optional<T>) Absent.INSTANCE;
75   }
76 
77   /**
78    * Returns an {@code Optional} instance containing the given non-null reference.
79    */
of(T reference)80   public static <T> Optional<T> of(T reference) {
81     return new Present<T>(checkNotNull(reference));
82   }
83 
84   /**
85    * If {@code nullableReference} is non-null, returns an {@code Optional} instance containing that
86    * reference; otherwise returns {@link Optional#absent}.
87    */
fromNullable(T nullableReference)88   public static <T> Optional<T> fromNullable(T nullableReference) {
89     return (nullableReference == null)
90         ? Optional.<T>absent()
91         : new Present<T>(nullableReference);
92   }
93 
Optional()94   Optional() {}
95 
96   /**
97    * Returns {@code true} if this holder contains a (non-null) instance.
98    */
isPresent()99   public abstract boolean isPresent();
100 
101   /**
102    * Returns the contained instance, which must be present. If the instance might be
103    * absent, use {@link #or(Object)} or {@link #orNull} instead.
104    *
105    * @throws IllegalStateException if the instance is absent ({@link #isPresent} returns
106    *     {@code false})
107    */
get()108   public abstract T get();
109 
110   /**
111    * Returns the contained instance if it is present; {@code defaultValue} otherwise. If
112    * no default value should be required because the instance is known to be present, use
113    * {@link #get()} instead. For a default value of {@code null}, use {@link #orNull}.
114    *
115    * <p>Note about generics: The signature {@code public T or(T defaultValue)} is overly
116    * restrictive. However, the ideal signature, {@code public <S super T> S or(S)}, is not legal
117    * Java. As a result, some sensible operations involving subtypes are compile errors:
118    * <pre>   {@code
119    *
120    *   Optional<Integer> optionalInt = getSomeOptionalInt();
121    *   Number value = optionalInt.or(0.5); // error
122    *
123    *   FluentIterable<? extends Number> numbers = getSomeNumbers();
124    *   Optional<? extends Number> first = numbers.first();
125    *   Number value = first.or(0.5); // error}</pre>
126    *
127    * As a workaround, it is always safe to cast an {@code Optional<? extends T>} to {@code
128    * Optional<T>}. Casting either of the above example {@code Optional} instances to {@code
129    * Optional<Number>} (where {@code Number} is the desired output type) solves the problem:
130    * <pre>   {@code
131    *
132    *   Optional<Number> optionalInt = (Optional) getSomeOptionalInt();
133    *   Number value = optionalInt.or(0.5); // fine
134    *
135    *   FluentIterable<? extends Number> numbers = getSomeNumbers();
136    *   Optional<Number> first = (Optional) numbers.first();
137    *   Number value = first.or(0.5); // fine}</pre>
138    */
or(T defaultValue)139   public abstract T or(T defaultValue);
140 
141   /**
142    * Returns this {@code Optional} if it has a value present; {@code secondChoice}
143    * otherwise.
144    */
or(Optional<? extends T> secondChoice)145   public abstract Optional<T> or(Optional<? extends T> secondChoice);
146 
147   /**
148    * Returns the contained instance if it is present; {@code supplier.get()} otherwise. If the
149    * supplier returns {@code null}, a {@link NullPointerException} is thrown.
150    *
151    * @throws NullPointerException if the supplier returns {@code null}
152    */
or(Supplier<? extends T> supplier)153   public abstract T or(Supplier<? extends T> supplier);
154 
155   /**
156    * Returns the contained instance if it is present; {@code null} otherwise. If the
157    * instance is known to be present, use {@link #get()} instead.
158    */
orNull()159   public abstract T orNull();
160 
161   /**
162    * Returns an immutable singleton {@link Set} whose only element is the contained instance
163    * if it is present; an empty immutable {@link Set} otherwise.
164    *
165    * @since 11.0
166    */
asSet()167   public abstract Set<T> asSet();
168 
169   /**
170    * If the instance is present, it is transformed with the given {@link Function}; otherwise,
171    * {@link Optional#absent} is returned. If the function returns {@code null}, a
172    * {@link NullPointerException} is thrown.
173    *
174    * @throws NullPointerException if the function returns {@code null}
175    *
176    * @since 12.0
177    */
178 
transform(Function<? super T, V> function)179   public abstract <V> Optional<V> transform(Function<? super T, V> function);
180 
181   /**
182    * Returns {@code true} if {@code object} is an {@code Optional} instance, and either
183    * the contained references are {@linkplain Object#equals equal} to each other or both
184    * are absent. Note that {@code Optional} instances of differing parameterized types can
185    * be equal.
186    */
equals(Object object)187   @Override public abstract boolean equals(Object object);
188 
189   /**
190    * Returns a hash code for this instance.
191    */
hashCode()192   @Override public abstract int hashCode();
193 
194   /**
195    * Returns a string representation for this instance. The form of this string
196    * representation is unspecified.
197    */
toString()198   @Override public abstract String toString();
199 
200   /**
201    * Returns the value of each present instance from the supplied {@code optionals}, in order,
202    * skipping over occurrences of {@link Optional#absent}. Iterators are unmodifiable and are
203    * evaluated lazily.
204    *
205    * @since 11.0 (generics widened in 13.0)
206    */
207 
208 //  public static <T> Iterable<T> presentInstances(
209 //      final Iterable<? extends Optional<? extends T>> optionals) {
210 //    checkNotNull(optionals);
211 //    return new Iterable<T>() {
212 //      @Override public Iterator<T> iterator() {
213 //        return new AbstractIterator<T>() {
214 //          private final Iterator<? extends Optional<? extends T>> iterator =
215 //              checkNotNull(optionals.iterator());
216 //
217 //          @Override protected T computeNext() {
218 //            while (iterator.hasNext()) {
219 //              Optional<? extends T> optional = iterator.next();
220 //              if (optional.isPresent()) {
221 //                return optional.get();
222 //              }
223 //            }
224 //            return endOfData();
225 //          }
226 //        };
227 //      };
228 //    };
229 //  }
230 
231   private static final long serialVersionUID = 0;
232 }
233