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