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
026 import javax.annotation.Nullable;
027
028 /**
029 * An immutable object that may contain a non-null reference to another object. Each
030 * instance of this type either contains a non-null reference, or contains nothing (in
031 * which case we say that the reference is "absent"); it is never said to "contain {@code
032 * null}".
033 *
034 * <p>A non-null {@code Optional<T>} reference can be used as a replacement for a nullable
035 * {@code T} reference. It allows you to represent "a {@code T} that must be present" and
036 * a "a {@code T} that might be absent" as two distinct types in your program, which can
037 * aid clarity.
038 *
039 * <p>Some uses of this class include
040 *
041 * <ul>
042 * <li>As a method return type, as an alternative to returning {@code null} to indicate
043 * that no value was available
044 * <li>To distinguish between "unknown" (for example, not present in a map) and "known to
045 * have no value" (present in the map, with value {@code Optional.absent()})
046 * <li>To wrap nullable references for storage in a collection that does not support
047 * {@code null} (though there are
048 * <a href="http://code.google.com/p/guava-libraries/wiki/LivingWithNullHostileCollections">
049 * several other approaches to this</a> that should be considered first)
050 * </ul>
051 *
052 * <p>A common alternative to using this class is to find or create a suitable
053 * <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">null object</a> for the
054 * type in question.
055 *
056 * <p>This class is not intended as a direct analogue of any existing "option" or "maybe"
057 * construct from other programming environments, though it may bear some similarities.
058 *
059 *
060 * @param <T> the type of instance that can be contained. {@code Optional} is naturally
061 * covariant on this type, so it is safe to cast an {@code Optional<T>} to {@code
062 * Optional<S>} for any supertype {@code S} of {@code T}.
063 * @author Kurt Alfred Kluever
064 * @author Kevin Bourrillion
065 * @since 10.0
066 */
067 @Beta
068 @GwtCompatible
069 public abstract class Optional<T> implements Serializable {
070 /**
071 * Returns an {@code Optional} instance with no contained reference.
072 */
073 @SuppressWarnings("unchecked")
074 public static <T> Optional<T> absent() {
075 return (Optional<T>) Absent.INSTANCE;
076 }
077
078 /**
079 * Returns an {@code Optional} instance containing the given non-null reference.
080 */
081 public static <T> Optional<T> of(T reference) {
082 return new Present<T>(checkNotNull(reference));
083 }
084
085 /**
086 * If {@code nullableReference} is non-null, returns an {@code Optional} instance containing that
087 * reference; otherwise returns {@link Optional#absent}.
088 */
089 public static <T> Optional<T> fromNullable(@Nullable T nullableReference) {
090 return (nullableReference == null)
091 ? Optional.<T>absent()
092 : new Present<T>(nullableReference);
093 }
094
095 private Optional() {}
096
097 /**
098 * Returns {@code true} if this holder contains a (non-null) instance.
099 */
100 public abstract boolean isPresent();
101
102 // TODO(kevinb): isAbsent too?
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.
128 */
129 @Nullable public abstract T or(Supplier<? extends T> supplier);
130
131 /**
132 * Returns the contained instance if it is present; {@code null} otherwise. If the
133 * instance is known to be present, use {@link #get()} instead.
134 */
135 @Nullable public abstract T orNull();
136
137 /**
138 * Returns {@code true} if {@code object} is an {@code Optional} instance, and either
139 * the contained references are {@linkplain Object#equals equal} to each other or both
140 * are absent. Note that {@code Optional} instances of differing parameterized types can
141 * be equal.
142 */
143 @Override public abstract boolean equals(@Nullable Object object);
144
145 /**
146 * Returns a hash code for this instance.
147 */
148 @Override public abstract int hashCode();
149
150 /**
151 * Returns a string representation for this instance. The form of this string
152 * representation is unspecified.
153 */
154 @Override public abstract String toString();
155
156 private static final long serialVersionUID = 0;
157
158 private static final class Present<T> extends Optional<T> {
159 private final T reference;
160
161 Present(T reference) {
162 this.reference = reference;
163 }
164
165 @Override public boolean isPresent() {
166 return true;
167 }
168
169 @Override public T get() {
170 return reference;
171 }
172
173 @Override public T or(T defaultValue) {
174 checkNotNull(defaultValue, "use orNull() instead of or(null)");
175 return reference;
176 }
177
178 @Override public Optional<T> or(Optional<? extends T> secondChoice) {
179 checkNotNull(secondChoice);
180 return this;
181 }
182
183 @Override public T or(Supplier<? extends T> supplier) {
184 checkNotNull(supplier);
185 return reference;
186 }
187
188 @Override public T orNull() {
189 return reference;
190 }
191
192 @Override public boolean equals(@Nullable Object object) {
193 if (object instanceof Present) {
194 Present<?> other = (Present<?>) object;
195 return reference.equals(other.reference);
196 }
197 return false;
198 }
199
200 @Override public int hashCode() {
201 return 0x598df91c + reference.hashCode();
202 }
203
204 @Override public String toString() {
205 return "Optional.of(" + reference + ")";
206 }
207
208 private static final long serialVersionUID = 0;
209 }
210
211 private static final class Absent extends Optional<Object> {
212 private static final Absent INSTANCE = new Absent();
213
214 @Override public boolean isPresent() {
215 return false;
216 }
217
218 @Override public Object get() {
219 throw new IllegalStateException("value is absent");
220 }
221
222 @Override public Object or(Object defaultValue) {
223 return checkNotNull(defaultValue, "use orNull() instead of or(null)");
224 }
225
226 @SuppressWarnings("unchecked") // safe covariant cast
227 @Override public Optional<Object> or(Optional<?> secondChoice) {
228 return (Optional) checkNotNull(secondChoice);
229 }
230
231 @Override @Nullable public Object or(Supplier<?> supplier) {
232 return supplier.get();
233 }
234
235 @Override @Nullable public Object orNull() {
236 return null;
237 }
238
239 @Override public boolean equals(@Nullable Object object) {
240 return object == this;
241 }
242
243 @Override public int hashCode() {
244 return 0x598df91c;
245 }
246
247 @Override public String toString() {
248 return "Optional.absent()";
249 }
250
251 private Object readResolve() {
252 return INSTANCE;
253 }
254
255 private static final long serialVersionUID = 0;
256 }
257 }