View Javadoc
1   /*
2    * Copyright (C) 2011 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  
15  package com.google.common.base;
16  
17  import static com.google.common.base.Preconditions.checkNotNull;
18  
19  import com.google.common.annotations.Beta;
20  import com.google.common.annotations.GwtCompatible;
21  import java.io.Serializable;
22  import java.util.Iterator;
23  import java.util.Set;
24  import javax.annotation.Nullable;
25  
26  /**
27   * An immutable object that may contain a non-null reference to another object. Each instance of
28   * this type either contains a non-null reference, or contains nothing (in which case we say that
29   * 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 {@code T}
33   * reference. It allows you to represent "a {@code T} that must be present" and a
34   * "a {@code T} that might be absent" as two distinct types in your program, which can aid clarity.
35   *
36   * <p>Some uses of this class include
37   *
38   * <ul>
39   * <li>As a method return type, as an alternative to returning {@code null} to indicate that no
40   *     value was available
41   * <li>To distinguish between "unknown" (for example, not present in a map) and "known to have no
42   *     value" (present in the map, with value {@code Optional.absent()})
43   * <li>To wrap nullable references for storage in a collection that does not support {@code null}
44   *     (though there are
45   *     <a href="https://github.com/google/guava/wiki/LivingWithNullHostileCollections">several other
46   *     approaches to this</a> that should be considered first)
47   * </ul>
48   *
49   * <p>A common alternative to using this class is to find or create a suitable
50   * <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">null object</a> for the type in
51   * question.
52   *
53   * <p>This class is not intended as a direct analogue of any existing "option" or "maybe" construct
54   * from other programming environments, though it may bear some similarities.
55   *
56   * <p><b>Comparison to {@code java.util.Optional} (JDK 8 and higher):</b> A new {@code Optional}
57   * class was added for Java 8. The two classes are extremely similar, but incompatible (they cannot
58   * share a common supertype). <i>All</i> known differences are listed either here or with the
59   * relevant methods below.
60   *
61   * <ul>
62   * <li>This class is serializable; {@code java.util.Optional} is not.
63   * <li>{@code java.util.Optional} has the additional methods {@code ifPresent}, {@code filter},
64   *     {@code flatMap}, and {@code orElseThrow}.
65   * <li>{@code java.util} offers the primitive-specialized versions {@code OptionalInt}, {@code
66   *     OptionalLong} and {@code OptionalDouble}, the use of which is recommended; Guava does not
67   *     have these.
68   * </ul>
69   *
70   * <p><b>There are no plans to deprecate this class in the foreseeable future.</b> However, we do
71   * gently recommend that you prefer the new, standard Java class whenever possible.
72   *
73   * <p>See the Guava User Guide article on
74   * <a href="https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained#optional">using
75   * {@code Optional}</a>.
76   *
77   * @param <T> the type of instance that can be contained. {@code Optional} is naturally covariant on
78   *     this type, so it is safe to cast an {@code Optional<T>} to {@code
79   *     Optional<S>} for any supertype {@code S} of {@code T}.
80   * @author Kurt Alfred Kluever
81   * @author Kevin Bourrillion
82   * @since 10.0
83   */
84  @GwtCompatible(serializable = true)
85  public abstract class Optional<T> implements Serializable {
86    /**
87     * Returns an {@code Optional} instance with no contained reference.
88     *
89     * <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's
90     * {@code Optional.empty}.
91     */
92    public static <T> Optional<T> absent() {
93      return Absent.withType();
94    }
95  
96    /**
97     * Returns an {@code Optional} instance containing the given non-null reference. To have {@code
98     * null} treated as {@link #absent}, use {@link #fromNullable} instead.
99     *
100    * <p><b>Comparison to {@code java.util.Optional}:</b> no differences.
101    *
102    * @throws NullPointerException if {@code reference} is null
103    */
104   public static <T> Optional<T> of(T reference) {
105     return new Present<T>(checkNotNull(reference));
106   }
107 
108   /**
109    * If {@code nullableReference} is non-null, returns an {@code Optional} instance containing that
110    * reference; otherwise returns {@link Optional#absent}.
111    *
112    * <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's
113    * {@code Optional.ofNullable}.
114    */
115   public static <T> Optional<T> fromNullable(@Nullable T nullableReference) {
116     return (nullableReference == null)
117         ? Optional.<T>absent()
118         : new Present<T>(nullableReference);
119   }
120 
121   /**
122    * Returns the equivalent {@code com.google.common.base.Optional} value to the given {@code
123    * java.util.Optional}, or {@code null} if the argument is null.
124    *
125    * @since 21.0
126    */
127   @Nullable
128   public static <T> Optional<T> fromJavaUtil(@Nullable java.util.Optional<T> javaUtilOptional) {
129     return (javaUtilOptional == null) ? null : fromNullable(javaUtilOptional.orElse(null));
130   }
131 
132   /**
133    * Returns the equivalent {@code java.util.Optional} value to the given {@code
134    * com.google.common.base.Optional}, or {@code null} if the argument is null.
135    *
136    * <p>If {@code googleOptional} is known to be non-null, use {@code googleOptional.toJavaUtil()}
137    * instead.
138    *
139    * <p>Unfortunately, the method reference {@code Optional::toJavaUtil} will not work, because it
140    * could refer to either the static or instance version of this method. Write out the lambda
141    * expression {@code o -> Optional.toJavaUtil(o)} instead.
142    *
143    * @since 21.0
144    */
145   @Nullable
146   public static <T> java.util.Optional<T> toJavaUtil(@Nullable Optional<T> googleOptional) {
147     return googleOptional == null ? null : googleOptional.toJavaUtil();
148   }
149 
150   Optional() {}
151 
152   /**
153    * Returns {@code true} if this holder contains a (non-null) instance.
154    *
155    * <p><b>Comparison to {@code java.util.Optional}:</b> no differences.
156    */
157   public abstract boolean isPresent();
158 
159   /**
160    * Returns the contained instance, which must be present. If the instance might be absent, use
161    * {@link #or(Object)} or {@link #orNull} instead.
162    *
163    * <p><b>Comparison to {@code java.util.Optional}:</b> when the value is absent, this method
164    * throws {@link IllegalStateException}, whereas the Java 8 counterpart throws
165    * {@link java.util.NoSuchElementException NoSuchElementException}.
166    *
167    * @throws IllegalStateException if the instance is absent ({@link #isPresent} returns
168    *     {@code false}); depending on this <i>specific</i> exception type (over the more general
169    *     {@link RuntimeException}) is discouraged
170    */
171   public abstract T get();
172 
173   /**
174    * Returns the contained instance if it is present; {@code defaultValue} otherwise. If no default
175    * value should be required because the instance is known to be present, use {@link #get()}
176    * instead. For a default value of {@code null}, use {@link #orNull}.
177    *
178    * <p>Note about generics: The signature {@code public T or(T defaultValue)} is overly
179    * restrictive. However, the ideal signature, {@code public <S super T> S or(S)}, is not legal
180    * Java. As a result, some sensible operations involving subtypes are compile errors:
181    * <pre>   {@code
182    *
183    *   Optional<Integer> optionalInt = getSomeOptionalInt();
184    *   Number value = optionalInt.or(0.5); // error
185    *
186    *   FluentIterable<? extends Number> numbers = getSomeNumbers();
187    *   Optional<? extends Number> first = numbers.first();
188    *   Number value = first.or(0.5); // error}</pre>
189    *
190    * <p>As a workaround, it is always safe to cast an {@code Optional<? extends T>} to {@code
191    * Optional<T>}. Casting either of the above example {@code Optional} instances to {@code
192    * Optional<Number>} (where {@code Number} is the desired output type) solves the problem:
193    * <pre>   {@code
194    *
195    *   Optional<Number> optionalInt = (Optional) getSomeOptionalInt();
196    *   Number value = optionalInt.or(0.5); // fine
197    *
198    *   FluentIterable<? extends Number> numbers = getSomeNumbers();
199    *   Optional<Number> first = (Optional) numbers.first();
200    *   Number value = first.or(0.5); // fine}</pre>
201    *
202    * <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's
203    * {@code Optional.orElse}, but will not accept {@code null} as a {@code defaultValue}
204    * ({@link #orNull} must be used instead). As a result, the value returned by this method is
205    * guaranteed non-null, which is not the case for the {@code java.util} equivalent.
206    */
207   public abstract T or(T defaultValue);
208 
209   /**
210    * Returns this {@code Optional} if it has a value present; {@code secondChoice} otherwise.
211    *
212    * <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's
213    * {@code Optional} class; write {@code thisOptional.isPresent() ? thisOptional : secondChoice}
214    * instead.
215    */
216   public abstract Optional<T> or(Optional<? extends T> secondChoice);
217 
218   /**
219    * Returns the contained instance if it is present; {@code supplier.get()} otherwise.
220    *
221    * <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's
222    * {@code Optional.orElseGet}, except when {@code supplier} returns {@code null}. In this case
223    * this method throws an exception, whereas the Java 8 method returns the {@code null} to the
224    * caller.
225    *
226    * @throws NullPointerException if this optional's value is absent and the supplier returns
227    *     {@code null}
228    */
229   @Beta
230   public abstract T or(Supplier<? extends T> supplier);
231 
232   /**
233    * Returns the contained instance if it is present; {@code null} otherwise. If the instance is
234    * known to be present, use {@link #get()} instead.
235    *
236    * <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's
237    * {@code Optional.orElse(null)}.
238    */
239   @Nullable
240   public abstract T orNull();
241 
242   /**
243    * Returns an immutable singleton {@link Set} whose only element is the contained instance if it
244    * is present; an empty immutable {@link Set} otherwise.
245    *
246    * <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's
247    * {@code Optional} class. However, this common usage: <pre>   {@code
248    *
249    *   for (Foo foo : possibleFoo.asSet()) {
250    *     doSomethingWith(foo);
251    *   }}</pre>
252    *
253    * ... can be replaced with: <pre>   {@code
254    *
255    *   possibleFoo.ifPresent(foo -> doSomethingWith(foo));}</pre>
256    *
257    * @since 11.0
258    */
259   public abstract Set<T> asSet();
260 
261   /**
262    * If the instance is present, it is transformed with the given {@link Function}; otherwise,
263    * {@link Optional#absent} is returned.
264    *
265    * <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's
266    * {@code Optional.map}, except when {@code function} returns {@code null}. In this case this
267    * method throws an exception, whereas the Java 8 method returns {@code Optional.absent()}.
268    *
269    * @throws NullPointerException if the function returns {@code null}
270    * @since 12.0
271    */
272   public abstract <V> Optional<V> transform(Function<? super T, V> function);
273 
274   /**
275    * Returns the equivalent {@code java.util.Optional} value to this optional.
276    *
277    * <p>Unfortunately, the method reference {@code Optional::toJavaUtil} will not work, because it
278    * could refer to either the static or instance version of this method. Write out the lambda
279    * expression {@code o -> o.toJavaUtil()} instead.
280    *
281    * @since 21.0
282    */
283   public java.util.Optional<T> toJavaUtil() {
284     return java.util.Optional.ofNullable(orNull());
285   }
286 
287   /**
288    * Returns {@code true} if {@code object} is an {@code Optional} instance, and either the
289    * contained references are {@linkplain Object#equals equal} to each other or both are absent.
290    * Note that {@code Optional} instances of differing parameterized types can be equal.
291    *
292    * <p><b>Comparison to {@code java.util.Optional}:</b> no differences.
293    */
294   @Override
295   public abstract boolean equals(@Nullable Object object);
296 
297   /**
298    * Returns a hash code for this instance.
299    *
300    * <p><b>Comparison to {@code java.util.Optional}:</b> this class leaves the specific choice of
301    * hash code unspecified, unlike the Java 8 equivalent.
302    */
303   @Override
304   public abstract int hashCode();
305 
306   /**
307    * Returns a string representation for this instance.
308    *
309    * <p><b>Comparison to {@code java.util.Optional}:</b> this class leaves the specific string
310    * representation unspecified, unlike the Java 8 equivalent.
311    */
312   @Override
313   public abstract String toString();
314 
315   /**
316    * Returns the value of each present instance from the supplied {@code optionals}, in order,
317    * skipping over occurrences of {@link Optional#absent}. Iterators are unmodifiable and are
318    * evaluated lazily.
319    *
320    * <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's
321    * {@code Optional} class; use
322    * {@code optionals.stream().filter(Optional::isPresent).map(Optional::get)} instead.
323    *
324    * @since 11.0 (generics widened in 13.0)
325    */
326   @Beta
327   public static <T> Iterable<T> presentInstances(
328       final Iterable<? extends Optional<? extends T>> optionals) {
329     checkNotNull(optionals);
330     return new Iterable<T>() {
331       @Override
332       public Iterator<T> iterator() {
333         return new AbstractIterator<T>() {
334           private final Iterator<? extends Optional<? extends T>> iterator =
335               checkNotNull(optionals.iterator());
336 
337           @Override
338           protected T computeNext() {
339             while (iterator.hasNext()) {
340               Optional<? extends T> optional = iterator.next();
341               if (optional.isPresent()) {
342                 return optional.get();
343               }
344             }
345             return endOfData();
346           }
347         };
348       }
349     };
350   }
351 
352   private static final long serialVersionUID = 0;
353 }