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