|
| 1 | +/* |
| 2 | + * Copyright (C) 2011 The Guava Authors |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.google.common.base; |
| 18 | + |
| 19 | +import static com.google.common.base.Preconditions.checkNotNull; |
| 20 | + |
| 21 | +import com.google.common.annotations.Beta; |
| 22 | +import com.google.common.annotations.GwtCompatible; |
| 23 | + |
| 24 | +import java.io.Serializable; |
| 25 | +import java.util.Iterator; |
| 26 | +import java.util.Set; |
| 27 | + |
| 28 | +import javax.annotation.Nullable; |
| 29 | + |
| 30 | +/** |
| 31 | + * An immutable object that may contain a non-null reference to another object. Each |
| 32 | + * instance of this type either contains a non-null reference, or contains nothing (in |
| 33 | + * which case we say that the reference is "absent"); it is never said to "contain {@code |
| 34 | + * null}". |
| 35 | + * |
| 36 | + * <p>A non-null {@code Optional<T>} reference can be used as a replacement for a nullable |
| 37 | + * {@code T} reference. It allows you to represent "a {@code T} that must be present" and |
| 38 | + * a "a {@code T} that might be absent" as two distinct types in your program, which can |
| 39 | + * aid clarity. |
| 40 | + * |
| 41 | + * <p>Some uses of this class include |
| 42 | + * |
| 43 | + * <ul> |
| 44 | + * <li>As a method return type, as an alternative to returning {@code null} to indicate |
| 45 | + * that no value was available |
| 46 | + * <li>To distinguish between "unknown" (for example, not present in a map) and "known to |
| 47 | + * have no value" (present in the map, with value {@code Optional.absent()}) |
| 48 | + * <li>To wrap nullable references for storage in a collection that does not support |
| 49 | + * {@code null} (though there are |
| 50 | + * <a href="http://code.google.com/p/guava-libraries/wiki/LivingWithNullHostileCollections"> |
| 51 | + * several other approaches to this</a> that should be considered first) |
| 52 | + * </ul> |
| 53 | + * |
| 54 | + * <p>A common alternative to using this class is to find or create a suitable |
| 55 | + * <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">null object</a> for the |
| 56 | + * type in question. |
| 57 | + * |
| 58 | + * <p>This class is not intended as a direct analogue of any existing "option" or "maybe" |
| 59 | + * construct from other programming environments, though it may bear some similarities. |
| 60 | + * |
| 61 | + * <p>See the Guava User Guide article on <a |
| 62 | + * href="http://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained#Optional"> |
| 63 | + * using {@code Optional}</a>. |
| 64 | + * |
| 65 | + * @param <T> the type of instance that can be contained. {@code Optional} is naturally |
| 66 | + * covariant on this type, so it is safe to cast an {@code Optional<T>} to {@code |
| 67 | + * Optional<S>} for any supertype {@code S} of {@code T}. |
| 68 | + * @author Kurt Alfred Kluever |
| 69 | + * @author Kevin Bourrillion |
| 70 | + * @since 10.0 |
| 71 | + */ |
| 72 | +@GwtCompatible(serializable = true) |
| 73 | +public abstract class Optional<T> implements Serializable { |
| 74 | + /** |
| 75 | + * Returns an {@code Optional} instance with no contained reference. |
| 76 | + */ |
| 77 | + @SuppressWarnings("unchecked") |
| 78 | + public static <T> Optional<T> absent() { |
| 79 | + return (Optional<T>) Absent.INSTANCE; |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * Returns an {@code Optional} instance containing the given non-null reference. |
| 84 | + */ |
| 85 | + public static <T> Optional<T> of(T reference) { |
| 86 | + return new Present<T>(checkNotNull(reference)); |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * If {@code nullableReference} is non-null, returns an {@code Optional} instance containing that |
| 91 | + * reference; otherwise returns {@link Optional#absent}. |
| 92 | + */ |
| 93 | + public static <T> Optional<T> fromNullable(@Nullable T nullableReference) { |
| 94 | + return (nullableReference == null) |
| 95 | + ? Optional.<T>absent() |
| 96 | + : new Present<T>(nullableReference); |
| 97 | + } |
| 98 | + |
| 99 | + 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 | + public abstract Optional<T> or(Optional<? extends T> secondChoice); |
| 151 | + |
| 152 | + /** |
| 153 | + * Returns the contained instance if it is present; {@code supplier.get()} otherwise. If the |
| 154 | + * supplier returns {@code null}, a {@link NullPointerException} is thrown. |
| 155 | + * |
| 156 | + * @throws NullPointerException if the supplier returns {@code null} |
| 157 | + */ |
| 158 | + @Beta |
| 159 | + public abstract T or(Supplier<? extends T> supplier); |
| 160 | + |
| 161 | + /** |
| 162 | + * Returns the contained instance if it is present; {@code null} otherwise. If the |
| 163 | + * instance is known to be present, use {@link #get()} instead. |
| 164 | + */ |
| 165 | + @Nullable |
| 166 | + public abstract T orNull(); |
| 167 | + |
| 168 | + /** |
| 169 | + * Returns an immutable singleton {@link Set} whose only element is the contained instance |
| 170 | + * if it is present; an empty immutable {@link Set} otherwise. |
| 171 | + * |
| 172 | + * @since 11.0 |
| 173 | + */ |
| 174 | + public abstract Set<T> asSet(); |
| 175 | + |
| 176 | + /** |
| 177 | + * If the instance is present, it is transformed with the given {@link Function}; otherwise, |
| 178 | + * {@link Optional#absent} is returned. If the function returns {@code null}, a |
| 179 | + * {@link NullPointerException} is thrown. |
| 180 | + * |
| 181 | + * @throws NullPointerException if the function returns {@code null} |
| 182 | + * |
| 183 | + * @since 12.0 |
| 184 | + */ |
| 185 | + public abstract <V> Optional<V> transform(Function<? super T, V> function); |
| 186 | + |
| 187 | + /** |
| 188 | + * Returns {@code true} if {@code object} is an {@code Optional} instance, and either |
| 189 | + * the contained references are {@linkplain Object#equals equal} to each other or both |
| 190 | + * are absent. Note that {@code Optional} instances of differing parameterized types can |
| 191 | + * be equal. |
| 192 | + */ |
| 193 | + @Override |
| 194 | + public abstract boolean equals(@Nullable Object object); |
| 195 | + |
| 196 | + /** |
| 197 | + * Returns a hash code for this instance. |
| 198 | + */ |
| 199 | + @Override |
| 200 | + public abstract int hashCode(); |
| 201 | + |
| 202 | + /** |
| 203 | + * Returns a string representation for this instance. The form of this string |
| 204 | + * representation is unspecified. |
| 205 | + */ |
| 206 | + @Override |
| 207 | + public abstract String toString(); |
| 208 | + |
| 209 | + /** |
| 210 | + * Returns the value of each present instance from the supplied {@code optionals}, in order, |
| 211 | + * skipping over occurrences of {@link Optional#absent}. Iterators are unmodifiable and are |
| 212 | + * evaluated lazily. |
| 213 | + * |
| 214 | + * @since 11.0 (generics widened in 13.0) |
| 215 | + */ |
| 216 | + @Beta |
| 217 | + public static <T> Iterable<T> presentInstances( |
| 218 | + final Iterable<? extends Optional<? extends T>> optionals) { |
| 219 | + checkNotNull(optionals); |
| 220 | + return new Iterable<T>() { |
| 221 | + @Override |
| 222 | + public Iterator<T> iterator() { |
| 223 | + return new AbstractIterator<T>() { |
| 224 | + private final Iterator<? extends Optional<? extends T>> iterator = |
| 225 | + checkNotNull(optionals.iterator()); |
| 226 | + |
| 227 | + @Override |
| 228 | + protected T computeNext() { |
| 229 | + while (iterator.hasNext()) { |
| 230 | + Optional<? extends T> optional = iterator.next(); |
| 231 | + if (optional.isPresent()) { |
| 232 | + return optional.get(); |
| 233 | + } |
| 234 | + } |
| 235 | + return endOfData(); |
| 236 | + } |
| 237 | + }; |
| 238 | + } |
| 239 | + }; |
| 240 | + } |
| 241 | + |
| 242 | + private static final long serialVersionUID = 0; |
| 243 | +} |
0 commit comments