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