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.Collections;
026 import java.util.Iterator;
027 import java.util.Set;
028
029 import 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="http://code.google.com/p/guava-libraries/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 * @param <T> the type of instance that can be contained. {@code Optional} is naturally
063 * covariant on this type, so it is safe to cast an {@code Optional<T>} to {@code
064 * Optional<S>} for any supertype {@code S} of {@code T}.
065 * @author Kurt Alfred Kluever
066 * @author Kevin Bourrillion
067 * @since 10.0
068 */
069 @Beta
070 @GwtCompatible
071 public abstract class Optional<T> implements Serializable {
072 /**
073 * Returns an {@code Optional} instance with no contained reference.
074 */
075 @SuppressWarnings("unchecked")
076 public static <T> Optional<T> absent() {
077 return (Optional<T>) Absent.INSTANCE;
078 }
079
080 /**
081 * Returns an {@code Optional} instance containing the given non-null reference.
082 */
083 public static <T> Optional<T> of(T reference) {
084 return new Present<T>(checkNotNull(reference));
085 }
086
087 /**
088 * If {@code nullableReference} is non-null, returns an {@code Optional} instance containing that
089 * reference; otherwise returns {@link Optional#absent}.
090 */
091 public static <T> Optional<T> fromNullable(@Nullable T nullableReference) {
092 return (nullableReference == null)
093 ? Optional.<T>absent()
094 : new Present<T>(nullableReference);
095 }
096
097 private Optional() {}
098
099 /**
100 * Returns {@code true} if this holder contains a (non-null) instance.
101 */
102 public abstract boolean isPresent();
103
104 /**
105 * Returns the contained instance, which must be present. If the instance might be
106 * absent, use {@link #or(Object)} or {@link #orNull} instead.
107 *
108 * @throws IllegalStateException if the instance is absent ({@link #isPresent} returns
109 * {@code false})
110 */
111 public abstract T get();
112
113 /**
114 * Returns the contained instance if it is present; {@code defaultValue} otherwise. If
115 * no default value should be required because the instance is known to be present, use
116 * {@link #get()} instead. For a default value of {@code null}, use {@link #orNull}.
117 */
118 public abstract T or(T defaultValue);
119
120 /**
121 * Returns this {@code Optional} if it has a value present; {@code secondChoice}
122 * otherwise.
123 */
124 public abstract Optional<T> or(Optional<? extends T> secondChoice);
125
126 /**
127 * Returns the contained instance if it is present; {@code supplier.get()} otherwise. If the
128 * supplier returns {@code null}, a {@link NullPointerException} will be thrown.
129 *
130 * @throws NullPointerException if the supplier returns {@code null}
131 */
132 public abstract T or(Supplier<? extends T> supplier);
133
134 /**
135 * Returns the contained instance if it is present; {@code null} otherwise. If the
136 * instance is known to be present, use {@link #get()} instead.
137 */
138 @Nullable public abstract T orNull();
139
140 /**
141 * Returns an immutable singleton {@link Set} whose only element is the
142 * contained instance if it is present; an empty immutable {@link Set}
143 * otherwise.
144 *
145 * @since 11.0
146 */
147 public abstract Set<T> asSet();
148
149 /**
150 * Returns {@code true} if {@code object} is an {@code Optional} instance, and either
151 * the contained references are {@linkplain Object#equals equal} to each other or both
152 * are absent. Note that {@code Optional} instances of differing parameterized types can
153 * be equal.
154 */
155 @Override public abstract boolean equals(@Nullable Object object);
156
157 /**
158 * Returns a hash code for this instance.
159 */
160 @Override public abstract int hashCode();
161
162 /**
163 * Returns a string representation for this instance. The form of this string
164 * representation is unspecified.
165 */
166 @Override public abstract String toString();
167
168 /**
169 * Returns the value of each present instance from the supplied {@code optionals}, in order,
170 * skipping over occurrences of {@link Optional#absent}. Iterators are unmodifiable and are
171 * evaluated lazily.
172 *
173 * @since 11.0
174 */
175 public static <T> Iterable<T> presentInstances(Iterable<Optional<T>> optionals) {
176 checkNotNull(optionals);
177 final Iterator<Optional<T>> iterator = checkNotNull(optionals.iterator());
178 return new Iterable<T>() {
179 @Override public Iterator<T> iterator() {
180 return new AbstractIterator<T>() {
181 @Override protected T computeNext() {
182 while (iterator.hasNext()) {
183 Optional<T> optional = iterator.next();
184 if (optional.isPresent()) {
185 return optional.get();
186 }
187 }
188 return endOfData();
189 }
190 };
191 };
192 };
193 }
194
195 private static final long serialVersionUID = 0;
196
197 private static final class Present<T> extends Optional<T> {
198 private final T reference;
199
200 Present(T reference) {
201 this.reference = reference;
202 }
203
204 @Override public boolean isPresent() {
205 return true;
206 }
207
208 @Override public T get() {
209 return reference;
210 }
211
212 @Override public T or(T defaultValue) {
213 checkNotNull(defaultValue, "use orNull() instead of or(null)");
214 return reference;
215 }
216
217 @Override public Optional<T> or(Optional<? extends T> secondChoice) {
218 checkNotNull(secondChoice);
219 return this;
220 }
221
222 @Override public T or(Supplier<? extends T> supplier) {
223 checkNotNull(supplier);
224 return reference;
225 }
226
227 @Override public T orNull() {
228 return reference;
229 }
230
231 @Override public Set<T> asSet() {
232 return Collections.singleton(reference);
233 }
234
235 @Override public boolean equals(@Nullable Object object) {
236 if (object instanceof Present) {
237 Present<?> other = (Present<?>) object;
238 return reference.equals(other.reference);
239 }
240 return false;
241 }
242
243 @Override public int hashCode() {
244 return 0x598df91c + reference.hashCode();
245 }
246
247 @Override public String toString() {
248 return "Optional.of(" + reference + ")";
249 }
250
251 private static final long serialVersionUID = 0;
252 }
253
254 private static final class Absent extends Optional<Object> {
255 private static final Absent INSTANCE = new Absent();
256
257 @Override public boolean isPresent() {
258 return false;
259 }
260
261 @Override public Object get() {
262 throw new IllegalStateException("value is absent");
263 }
264
265 @Override public Object or(Object defaultValue) {
266 return checkNotNull(defaultValue, "use orNull() instead of or(null)");
267 }
268
269 @SuppressWarnings("unchecked") // safe covariant cast
270 @Override public Optional<Object> or(Optional<?> secondChoice) {
271 return (Optional) checkNotNull(secondChoice);
272 }
273
274 @Override public Object or(Supplier<?> supplier) {
275 return checkNotNull(supplier.get(),
276 "use orNull() instead of a Supplier that returns null");
277 }
278
279 @Override @Nullable public Object orNull() {
280 return null;
281 }
282
283 @Override public Set<Object> asSet() {
284 return Collections.emptySet();
285 }
286
287 @Override public boolean equals(@Nullable Object object) {
288 return object == this;
289 }
290
291 @Override public int hashCode() {
292 return 0x598df91c;
293 }
294
295 @Override public String toString() {
296 return "Optional.absent()";
297 }
298
299 private Object readResolve() {
300 return INSTANCE;
301 }
302
303 private static final long serialVersionUID = 0;
304 }
305 }