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