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