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