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