001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.base;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.Beta;
020import com.google.common.annotations.GwtCompatible;
021import com.google.errorprone.annotations.DoNotMock;
022import java.io.Serializable;
023import java.util.Iterator;
024import java.util.Set;
025import javax.annotation.CheckForNull;
026
027/**
028 * An immutable object that may contain a non-null reference to another object. Each instance of
029 * this type either contains a non-null reference, or contains nothing (in which case we say that
030 * the reference is "absent"); it is never said to "contain {@code null}".
031 *
032 * <p>A non-null {@code Optional<T>} reference can be used as a replacement for a nullable {@code T}
033 * reference. It allows you to represent "a {@code T} that must be present" and a "a {@code T} that
034 * might be absent" as two distinct types in your program, which can aid clarity.
035 *
036 * <p>Some uses of this class include
037 *
038 * <ul>
039 *   <li>As a method return type, as an alternative to returning {@code null} to indicate that no
040 *       value was available
041 *   <li>To distinguish between "unknown" (for example, not present in a map) and "known to have no
042 *       value" (present in the map, with value {@code Optional.absent()})
043 *   <li>To wrap nullable references for storage in a collection that does not support {@code null}
044 *       (though there are <a
045 *       href="https://github.com/google/guava/wiki/LivingWithNullHostileCollections">several other
046 *       approaches to this</a> that should be considered first)
047 * </ul>
048 *
049 * <p>A common alternative to using this class is to find or create a suitable <a
050 * href="http://en.wikipedia.org/wiki/Null_Object_pattern">null object</a> for the type in question.
051 *
052 * <p>This class is not intended as a direct analogue of any existing "option" or "maybe" construct
053 * from other programming environments, though it may bear some similarities.
054 *
055 * <p><b>Comparison to {@code java.util.Optional} (JDK 8 and higher):</b> A new {@code Optional}
056 * class was added for Java 8. The two classes are extremely similar, but incompatible (they cannot
057 * share a common supertype). <i>All</i> known differences are listed either here or with the
058 * relevant methods below.
059 *
060 * <ul>
061 *   <li>This class is serializable; {@code java.util.Optional} is not.
062 *   <li>{@code java.util.Optional} has the additional methods {@code ifPresent}, {@code filter},
063 *       {@code flatMap}, and {@code orElseThrow}.
064 *   <li>{@code java.util} offers the primitive-specialized versions {@code OptionalInt}, {@code
065 *       OptionalLong} and {@code OptionalDouble}, the use of which is recommended; Guava does not
066 *       have these.
067 * </ul>
068 *
069 * <p><b>There are no plans to deprecate this class in the foreseeable future.</b> However, we do
070 * gently recommend that you prefer the new, standard Java class whenever possible.
071 *
072 * <p>See the Guava User Guide article on <a
073 * href="https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained#optional">using {@code
074 * Optional}</a>.
075 *
076 * @param <T> the type of instance that can be contained. {@code Optional} is naturally covariant on
077 *     this type, so it is safe to cast an {@code Optional<T>} to {@code Optional<S>} for any
078 *     supertype {@code S} of {@code T}.
079 * @author Kurt Alfred Kluever
080 * @author Kevin Bourrillion
081 * @since 10.0
082 */
083@DoNotMock("Use Optional.of(value) or Optional.absent()")
084@GwtCompatible(serializable = true)
085@ElementTypesAreNonnullByDefault
086public abstract class Optional<T> implements Serializable {
087  /**
088   * Returns an {@code Optional} instance with no contained reference.
089   *
090   * <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's
091   * {@code Optional.empty}.
092   */
093  public static <T> Optional<T> absent() {
094    return Absent.withType();
095  }
096
097  /**
098   * Returns an {@code Optional} instance containing the given non-null reference. To have {@code
099   * null} treated as {@link #absent}, use {@link #fromNullable} instead.
100   *
101   * <p><b>Comparison to {@code java.util.Optional}:</b> no differences.
102   *
103   * @throws NullPointerException if {@code reference} is null
104   */
105  public static <T> Optional<T> of(T reference) {
106    return new Present<T>(checkNotNull(reference));
107  }
108
109  /**
110   * If {@code nullableReference} is non-null, returns an {@code Optional} instance containing that
111   * reference; otherwise returns {@link Optional#absent}.
112   *
113   * <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's
114   * {@code Optional.ofNullable}.
115   */
116  public static <T> Optional<T> fromNullable(@CheckForNull T nullableReference) {
117    return (nullableReference == null) ? Optional.<T>absent() : new Present<T>(nullableReference);
118  }
119
120  /**
121   * Returns the equivalent {@code com.google.common.base.Optional} value to the given {@code
122   * java.util.Optional}, or {@code null} if the argument is null.
123   *
124   * @since 21.0
125   */
126  @CheckForNull
127  public static <T> Optional<T> fromJavaUtil(@CheckForNull java.util.Optional<T> javaUtilOptional) {
128    return (javaUtilOptional == null) ? null : fromNullable(javaUtilOptional.orElse(null));
129  }
130
131  /**
132   * Returns the equivalent {@code java.util.Optional} value to the given {@code
133   * com.google.common.base.Optional}, or {@code null} if the argument is null.
134   *
135   * <p>If {@code googleOptional} is known to be non-null, use {@code googleOptional.toJavaUtil()}
136   * instead.
137   *
138   * <p>Unfortunately, the method reference {@code Optional::toJavaUtil} will not work, because it
139   * could refer to either the static or instance version of this method. Write out the lambda
140   * expression {@code o -> Optional.toJavaUtil(o)} instead.
141   *
142   * @since 21.0
143   */
144  @CheckForNull
145  public static <T> java.util.Optional<T> toJavaUtil(@CheckForNull Optional<T> googleOptional) {
146    return googleOptional == null ? null : googleOptional.toJavaUtil();
147  }
148
149  /**
150   * Returns the equivalent {@code java.util.Optional} value to this optional.
151   *
152   * <p>Unfortunately, the method reference {@code Optional::toJavaUtil} will not work, because it
153   * could refer to either the static or instance version of this method. Write out the lambda
154   * expression {@code o -> o.toJavaUtil()} instead.
155   *
156   * @since 21.0
157   */
158  public java.util.Optional<T> toJavaUtil() {
159    return java.util.Optional.ofNullable(orNull());
160  }
161
162  Optional() {}
163
164  /**
165   * Returns {@code true} if this holder contains a (non-null) instance.
166   *
167   * <p><b>Comparison to {@code java.util.Optional}:</b> no differences.
168   */
169  public abstract boolean isPresent();
170
171  /**
172   * Returns the contained instance, which must be present. If the instance might be absent, use
173   * {@link #or(Object)} or {@link #orNull} instead.
174   *
175   * <p><b>Comparison to {@code java.util.Optional}:</b> when the value is absent, this method
176   * throws {@link IllegalStateException}, whereas the Java 8 counterpart throws {@link
177   * java.util.NoSuchElementException NoSuchElementException}.
178   *
179   * @throws IllegalStateException if the instance is absent ({@link #isPresent} returns {@code
180   *     false}); depending on this <i>specific</i> exception type (over the more general {@link
181   *     RuntimeException}) is discouraged
182   */
183  public abstract T get();
184
185  /**
186   * Returns the contained instance if it is present; {@code defaultValue} otherwise. If no default
187   * value should be required because the instance is known to be present, use {@link #get()}
188   * instead. For a default value of {@code null}, use {@link #orNull}.
189   *
190   * <p>Note about generics: The signature {@code public T or(T defaultValue)} is overly
191   * restrictive. However, the ideal signature, {@code public <S super T> S or(S)}, is not legal
192   * Java. As a result, some sensible operations involving subtypes are compile errors:
193   *
194   * <pre>{@code
195   * Optional<Integer> optionalInt = getSomeOptionalInt();
196   * Number value = optionalInt.or(0.5); // error
197   *
198   * FluentIterable<? extends Number> numbers = getSomeNumbers();
199   * Optional<? extends Number> first = numbers.first();
200   * Number value = first.or(0.5); // error
201   * }</pre>
202   *
203   * <p>As a workaround, it is always safe to cast an {@code Optional<? extends T>} to {@code
204   * Optional<T>}. Casting either of the above example {@code Optional} instances to {@code
205   * Optional<Number>} (where {@code Number} is the desired output type) solves the problem:
206   *
207   * <pre>{@code
208   * Optional<Number> optionalInt = (Optional) getSomeOptionalInt();
209   * Number value = optionalInt.or(0.5); // fine
210   *
211   * FluentIterable<? extends Number> numbers = getSomeNumbers();
212   * Optional<Number> first = (Optional) numbers.first();
213   * Number value = first.or(0.5); // fine
214   * }</pre>
215   *
216   * <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's {@code
217   * Optional.orElse}, but will not accept {@code null} as a {@code defaultValue} ({@link #orNull}
218   * must be used instead). As a result, the value returned by this method is guaranteed non-null,
219   * which is not the case for the {@code java.util} equivalent.
220   */
221  public abstract T or(T defaultValue);
222
223  /**
224   * Returns this {@code Optional} if it has a value present; {@code secondChoice} otherwise.
225   *
226   * <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's
227   * {@code Optional} class; write {@code thisOptional.isPresent() ? thisOptional : secondChoice}
228   * instead.
229   */
230  public abstract Optional<T> or(Optional<? extends T> secondChoice);
231
232  /**
233   * Returns the contained instance if it is present; {@code supplier.get()} otherwise.
234   *
235   * <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's {@code
236   * Optional.orElseGet}, except when {@code supplier} returns {@code null}. In this case this
237   * method throws an exception, whereas the Java 8 method returns the {@code null} to the caller.
238   *
239   * @throws NullPointerException if this optional's value is absent and the supplier returns {@code
240   *     null}
241   */
242  @Beta
243  public abstract T or(Supplier<? extends T> supplier);
244
245  /**
246   * Returns the contained instance if it is present; {@code null} otherwise. If the instance is
247   * known to be present, use {@link #get()} instead.
248   *
249   * <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's
250   * {@code Optional.orElse(null)}.
251   */
252  @CheckForNull
253  public abstract T orNull();
254
255  /**
256   * Returns an immutable singleton {@link Set} whose only element is the contained instance if it
257   * is present; an empty immutable {@link Set} otherwise.
258   *
259   * <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's
260   * {@code Optional} class. However, this common usage:
261   *
262   * <pre>{@code
263   * for (Foo foo : possibleFoo.asSet()) {
264   *   doSomethingWith(foo);
265   * }
266   * }</pre>
267   *
268   * ... can be replaced with:
269   *
270   * <pre>{@code
271   * possibleFoo.ifPresent(foo -> doSomethingWith(foo));
272   * }</pre>
273   *
274   * <p><b>Java 9 users:</b> some use cases can be written with calls to {@code optional.stream()}.
275   *
276   * @since 11.0
277   */
278  public abstract Set<T> asSet();
279
280  /**
281   * If the instance is present, it is transformed with the given {@link Function}; otherwise,
282   * {@link Optional#absent} is returned.
283   *
284   * <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's {@code
285   * Optional.map}, except when {@code function} returns {@code null}. In this case this method
286   * throws an exception, whereas the Java 8 method returns {@code Optional.absent()}.
287   *
288   * @throws NullPointerException if the function returns {@code null}
289   * @since 12.0
290   */
291  public abstract <V> Optional<V> transform(Function<? super T, V> function);
292
293  /**
294   * Returns {@code true} if {@code object} is an {@code Optional} instance, and either the
295   * contained references are {@linkplain Object#equals equal} to each other or both are absent.
296   * Note that {@code Optional} instances of differing parameterized types can be equal.
297   *
298   * <p><b>Comparison to {@code java.util.Optional}:</b> no differences.
299   */
300  @Override
301  public abstract boolean equals(@CheckForNull Object object);
302
303  /**
304   * Returns a hash code for this instance.
305   *
306   * <p><b>Comparison to {@code java.util.Optional}:</b> this class leaves the specific choice of
307   * hash code unspecified, unlike the Java 8 equivalent.
308   */
309  @Override
310  public abstract int hashCode();
311
312  /**
313   * Returns a string representation for this instance.
314   *
315   * <p><b>Comparison to {@code java.util.Optional}:</b> this class leaves the specific string
316   * representation unspecified, unlike the Java 8 equivalent.
317   */
318  @Override
319  public abstract String toString();
320
321  /**
322   * Returns the value of each present instance from the supplied {@code optionals}, in order,
323   * skipping over occurrences of {@link Optional#absent}. Iterators are unmodifiable and are
324   * evaluated lazily.
325   *
326   * <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's
327   * {@code Optional} class; use {@code
328   * optionals.stream().filter(Optional::isPresent).map(Optional::get)} instead.
329   *
330   * <p><b>Java 9 users:</b> use {@code optionals.stream().flatMap(Optional::stream)} instead.
331   *
332   * @since 11.0 (generics widened in 13.0)
333   */
334  @Beta
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}