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    
017    package com.google.common.base;
018    
019    import static com.google.common.base.Preconditions.checkNotNull;
020    
021    import com.google.common.annotations.Beta;
022    import com.google.common.annotations.GwtCompatible;
023    
024    import java.io.Serializable;
025    import java.util.Iterator;
026    import java.util.Set;
027    
028    import javax.annotation.Nullable;
029    
030    /**
031     * An immutable object that may contain a non-null reference to another object. Each
032     * instance of this type either contains a non-null reference, or contains nothing (in
033     * which case we say that the reference is "absent"); it is never said to "contain {@code
034     * null}".
035     *
036     * <p>A non-null {@code Optional<T>} reference can be used as a replacement for a nullable
037     * {@code T} reference. It allows you to represent "a {@code T} that must be present" and
038     * a "a {@code T} that might be absent" as two distinct types in your program, which can
039     * aid clarity.
040     *
041     * <p>Some uses of this class include
042     *
043     * <ul>
044     * <li>As a method return type, as an alternative to returning {@code null} to indicate
045     *     that no value was available
046     * <li>To distinguish between "unknown" (for example, not present in a map) and "known to
047     *     have no value" (present in the map, with value {@code Optional.absent()})
048     * <li>To wrap nullable references for storage in a collection that does not support
049     *     {@code null} (though there are
050     *     <a href="http://code.google.com/p/guava-libraries/wiki/LivingWithNullHostileCollections">
051     *     several other approaches to this</a> that should be considered first)
052     * </ul>
053     *
054     * <p>A common alternative to using this class is to find or create a suitable
055     * <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">null object</a> for the
056     * type in question.
057     *
058     * <p>This class is not intended as a direct analogue of any existing "option" or "maybe"
059     * construct from other programming environments, though it may bear some similarities.
060     *
061     * <p>See the Guava User Guide article on <a
062     * href="http://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained#Optional">
063     * using {@code Optional}</a>.
064     *
065     * @param <T> the type of instance that can be contained. {@code Optional} is naturally
066     *     covariant on this type, so it is safe to cast an {@code Optional<T>} to {@code
067     *     Optional<S>} for any supertype {@code S} of {@code T}.
068     * @author Kurt Alfred Kluever
069     * @author Kevin Bourrillion
070     * @since 10.0
071     */
072    @GwtCompatible(serializable = true)
073    public abstract class Optional<T> implements Serializable {
074      /**
075       * Returns an {@code Optional} instance with no contained reference.
076       */
077      @SuppressWarnings("unchecked")
078      public static <T> Optional<T> absent() {
079        return (Optional<T>) Absent.INSTANCE;
080      }
081    
082      /**
083       * Returns an {@code Optional} instance containing the given non-null reference.
084       */
085      public static <T> Optional<T> of(T reference) {
086        return new Present<T>(checkNotNull(reference));
087      }
088    
089      /**
090       * If {@code nullableReference} is non-null, returns an {@code Optional} instance containing that
091       * reference; otherwise returns {@link Optional#absent}.
092       */
093      public static <T> Optional<T> fromNullable(@Nullable T nullableReference) {
094        return (nullableReference == null)
095            ? Optional.<T>absent()
096            : new Present<T>(nullableReference);
097      }
098    
099      Optional() {}
100    
101      /**
102       * Returns {@code true} if this holder contains a (non-null) instance.
103       */
104      public abstract boolean isPresent();
105    
106      /**
107       * Returns the contained instance, which must be present. If the instance might be
108       * absent, use {@link #or(Object)} or {@link #orNull} instead.
109       *
110       * @throws IllegalStateException if the instance is absent ({@link #isPresent} returns
111       *     {@code false})
112       */
113      public abstract T get();
114    
115      /**
116       * Returns the contained instance if it is present; {@code defaultValue} otherwise. If
117       * no default value should be required because the instance is known to be present, use
118       * {@link #get()} instead. For a default value of {@code null}, use {@link #orNull}.
119       *
120       * <p>Note about generics: The signature {@code public T or(T defaultValue)} is overly
121       * restrictive. However, the ideal signature, {@code public <S super T> S or(S)}, is not legal
122       * Java. As a result, some sensible operations involving subtypes are compile errors:
123       * <pre>   {@code
124       *
125       *   Optional<Integer> optionalInt = getSomeOptionalInt();
126       *   Number value = optionalInt.or(0.5); // error
127       *
128       *   FluentIterable<? extends Number> numbers = getSomeNumbers();
129       *   Optional<? extends Number> first = numbers.first();
130       *   Number value = first.or(0.5); // error}</pre>
131       *
132       * As a workaround, it is always safe to cast an {@code Optional<? extends T>} to {@code
133       * Optional<T>}. Casting either of the above example {@code Optional} instances to {@code
134       * Optional<Number>} (where {@code Number} is the desired output type) solves the problem:
135       * <pre>   {@code
136       *
137       *   Optional<Number> optionalInt = (Optional) getSomeOptionalInt();
138       *   Number value = optionalInt.or(0.5); // fine
139       *
140       *   FluentIterable<? extends Number> numbers = getSomeNumbers();
141       *   Optional<Number> first = (Optional) numbers.first();
142       *   Number value = first.or(0.5); // fine}</pre>
143       */
144      public abstract T or(T defaultValue);
145    
146      /**
147       * Returns this {@code Optional} if it has a value present; {@code secondChoice}
148       * otherwise.
149       */
150      @Beta
151      public abstract Optional<T> or(Optional<? extends T> secondChoice);
152    
153      /**
154       * Returns the contained instance if it is present; {@code supplier.get()} otherwise. If the
155       * supplier returns {@code null}, a {@link NullPointerException} is thrown.
156       *
157       * @throws NullPointerException if the supplier returns {@code null}
158       */
159      @Beta
160      public abstract T or(Supplier<? extends T> supplier);
161    
162      /**
163       * Returns the contained instance if it is present; {@code null} otherwise. If the
164       * instance is known to be present, use {@link #get()} instead.
165       */
166      @Nullable
167      public abstract T orNull();
168    
169      /**
170       * Returns an immutable singleton {@link Set} whose only element is the contained instance
171       * if it is present; an empty immutable {@link Set} otherwise.
172       *
173       * @since 11.0
174       */
175      public abstract Set<T> asSet();
176    
177      /**
178       * If the instance is present, it is transformed with the given {@link Function}; otherwise,
179       * {@link Optional#absent} is returned. If the function returns {@code null}, a
180       * {@link NullPointerException} is thrown.
181       *
182       * @throws NullPointerException if the function returns {@code null}
183       *
184       * @since 12.0
185       */
186      @Beta
187      public abstract <V> Optional<V> transform(Function<? super T, V> function);
188    
189      /**
190       * Returns {@code true} if {@code object} is an {@code Optional} instance, and either
191       * the contained references are {@linkplain Object#equals equal} to each other or both
192       * are absent. Note that {@code Optional} instances of differing parameterized types can
193       * be equal.
194       */
195      @Override
196      public abstract boolean equals(@Nullable Object object);
197    
198      /**
199       * Returns a hash code for this instance.
200       */
201      @Override
202      public abstract int hashCode();
203    
204      /**
205       * Returns a string representation for this instance. The form of this string
206       * representation is unspecified.
207       */
208      @Override
209      public abstract String toString();
210    
211      /**
212       * Returns the value of each present instance from the supplied {@code optionals}, in order,
213       * skipping over occurrences of {@link Optional#absent}. Iterators are unmodifiable and are
214       * evaluated lazily.
215       *
216       * @since 11.0 (generics widened in 13.0)
217       */
218      @Beta
219      public static <T> Iterable<T> presentInstances(
220          final Iterable<? extends Optional<? extends T>> optionals) {
221        checkNotNull(optionals);
222        return new Iterable<T>() {
223          @Override
224          public Iterator<T> iterator() {
225            return new AbstractIterator<T>() {
226              private final Iterator<? extends Optional<? extends T>> iterator =
227                  checkNotNull(optionals.iterator());
228    
229              @Override
230              protected T computeNext() {
231                while (iterator.hasNext()) {
232                  Optional<? extends T> optional = iterator.next();
233                  if (optional.isPresent()) {
234                    return optional.get();
235                  }
236                }
237                return endOfData();
238              }
239            };
240          };
241        };
242      }
243    
244      private static final long serialVersionUID = 0;
245    }