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 java.io.Serializable; 022import java.util.Iterator; 023import java.util.Set; 024import javax.annotation.Nullable; 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 030 * 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 034 * "a {@code T} that 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 045 * <a 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 050 * <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">null object</a> for the type in 051 * question. 052 * 053 * <p>This class is not intended as a direct analogue of any existing "option" or "maybe" construct 054 * from other programming environments, though it may bear some similarities. 055 * 056 * <p><b>Comparison to {@code java.util.Optional} (JDK 8 and higher):</b> A new {@code Optional} 057 * class was added for Java 8. The two classes are extremely similar, but incompatible (they cannot 058 * share a common supertype). <i>All</i> known differences are listed either here or with the 059 * relevant methods below. 060 * 061 * <ul> 062 * <li>This class is serializable; {@code java.util.Optional} is not. 063 * <li>{@code java.util.Optional} has the additional methods {@code ifPresent}, {@code filter}, 064 * {@code flatMap}, and {@code orElseThrow}. 065 * <li>{@code java.util} offers the primitive-specialized versions {@code OptionalInt}, {@code 066 * OptionalLong} and {@code OptionalDouble}, the use of which is recommended; Guava does not 067 * have these. 068 * </ul> 069 * 070 * <p><b>There are no plans to deprecate this class in the foreseeable future.</b> However, we do 071 * gently recommend that you prefer the new, standard Java class whenever possible. 072 * 073 * <p>See the Guava User Guide article on 074 * <a href="https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained#optional">using 075 * {@code Optional}</a>. 076 * 077 * @param <T> the type of instance that can be contained. {@code Optional} is naturally covariant on 078 * this type, so it is safe to cast an {@code Optional<T>} to {@code 079 * Optional<S>} for any supertype {@code S} of {@code T}. 080 * @author Kurt Alfred Kluever 081 * @author Kevin Bourrillion 082 * @since 10.0 083 */ 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) 117 ? Optional.<T>absent() 118 : new Present<T>(nullableReference); 119 } 120 121 Optional() {} 122 123 /** 124 * Returns {@code true} if this holder contains a (non-null) instance. 125 * 126 * <p><b>Comparison to {@code java.util.Optional}:</b> no differences. 127 */ 128 public abstract boolean isPresent(); 129 130 /** 131 * Returns the contained instance, which must be present. If the instance might be absent, use 132 * {@link #or(Object)} or {@link #orNull} instead. 133 * 134 * <p><b>Comparison to {@code java.util.Optional}:</b> when the value is absent, this method 135 * throws {@link IllegalStateException}, whereas the Java 8 counterpart throws 136 * {@link NoSuchElementException}. 137 * 138 * @throws IllegalStateException if the instance is absent ({@link #isPresent} returns 139 * {@code false}); depending on this <i>specific</i> exception type (over the more general 140 * {@link RuntimeException}) is discouraged 141 */ 142 public abstract T get(); 143 144 /** 145 * Returns the contained instance if it is present; {@code defaultValue} otherwise. If no default 146 * value should be required because the instance is known to be present, use {@link #get()} 147 * instead. For a default value of {@code null}, use {@link #orNull}. 148 * 149 * <p>Note about generics: The signature {@code public T or(T defaultValue)} is overly 150 * restrictive. However, the ideal signature, {@code public <S super T> S or(S)}, is not legal 151 * Java. As a result, some sensible operations involving subtypes are compile errors: 152 * <pre> {@code 153 * 154 * Optional<Integer> optionalInt = getSomeOptionalInt(); 155 * Number value = optionalInt.or(0.5); // error 156 * 157 * FluentIterable<? extends Number> numbers = getSomeNumbers(); 158 * Optional<? extends Number> first = numbers.first(); 159 * Number value = first.or(0.5); // error}</pre> 160 * 161 * <p>As a workaround, it is always safe to cast an {@code Optional<? extends T>} to {@code 162 * Optional<T>}. Casting either of the above example {@code Optional} instances to {@code 163 * Optional<Number>} (where {@code Number} is the desired output type) solves the problem: 164 * <pre> {@code 165 * 166 * Optional<Number> optionalInt = (Optional) getSomeOptionalInt(); 167 * Number value = optionalInt.or(0.5); // fine 168 * 169 * FluentIterable<? extends Number> numbers = getSomeNumbers(); 170 * Optional<Number> first = (Optional) numbers.first(); 171 * Number value = first.or(0.5); // fine}</pre> 172 * 173 * <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's 174 * {@code Optional.orElse}, but will not accept {@code null} as a {@code defaultValue} 175 * ({@link #orNull} must be used instead). As a result, the value returned by this method is 176 * guaranteed non-null, which is not the case for the {@code java.util} equivalent. 177 */ 178 public abstract T or(T defaultValue); 179 180 /** 181 * Returns this {@code Optional} if it has a value present; {@code secondChoice} otherwise. 182 * 183 * <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's 184 * {@code Optional} class; write {@code thisOptional.isPresent() ? thisOptional : secondChoice} 185 * instead. 186 */ 187 public abstract Optional<T> or(Optional<? extends T> secondChoice); 188 189 /** 190 * Returns the contained instance if it is present; {@code supplier.get()} otherwise. 191 * 192 * <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's 193 * {@code Optional.orElseGet}, except when {@code supplier} returns {@code null}. In this case 194 * this method throws an exception, whereas the Java 8 method returns the {@code null} to the 195 * caller. 196 * 197 * @throws NullPointerException if this optional's value is absent and the supplier returns 198 * {@code null} 199 */ 200 @Beta 201 public abstract T or(Supplier<? extends T> supplier); 202 203 /** 204 * Returns the contained instance if it is present; {@code null} otherwise. If the instance is 205 * known to be present, use {@link #get()} instead. 206 * 207 * <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's 208 * {@code Optional.orElse(null)}. 209 */ 210 @Nullable 211 public abstract T orNull(); 212 213 /** 214 * Returns an immutable singleton {@link Set} whose only element is the contained instance if it 215 * is present; an empty immutable {@link Set} otherwise. 216 * 217 * <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's 218 * {@code Optional} class. However, this common usage: <pre> {@code 219 * 220 * for (Foo foo : possibleFoo.asSet()) { 221 * doSomethingWith(foo); 222 * }}</pre> 223 * 224 * ... can be replaced with: <pre> {@code 225 * 226 * possibleFoo.ifPresent(foo -> doSomethingWith(foo));}</pre> 227 * 228 * @since 11.0 229 */ 230 public abstract Set<T> asSet(); 231 232 /** 233 * If the instance is present, it is transformed with the given {@link Function}; otherwise, 234 * {@link Optional#absent} is returned. 235 * 236 * <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's 237 * {@code Optional.map}, except when {@code function} returns {@code null}. In this case this 238 * method throws an exception, whereas the Java 8 method returns {@code Optional.absent()}. 239 * 240 * @throws NullPointerException if the function returns {@code null} 241 * @since 12.0 242 */ 243 public abstract <V> Optional<V> transform(Function<? super T, V> function); 244 245 /** 246 * Returns {@code true} if {@code object} is an {@code Optional} instance, and either the 247 * contained references are {@linkplain Object#equals equal} to each other or both are absent. 248 * Note that {@code Optional} instances of differing parameterized types can be equal. 249 * 250 * <p><b>Comparison to {@code java.util.Optional}:</b> no differences. 251 */ 252 @Override 253 public abstract boolean equals(@Nullable Object object); 254 255 /** 256 * Returns a hash code for this instance. 257 * 258 * <p><b>Comparison to {@code java.util.Optional}:</b> this class leaves the specific choice of 259 * hash code unspecified, unlike the Java 8 equivalent. 260 */ 261 @Override 262 public abstract int hashCode(); 263 264 /** 265 * Returns a string representation for this instance. 266 * 267 * <p><b>Comparison to {@code java.util.Optional}:</b> this class leaves the specific string 268 * representation unspecified, unlike the Java 8 equivalent. 269 */ 270 @Override 271 public abstract String toString(); 272 273 /** 274 * Returns the value of each present instance from the supplied {@code optionals}, in order, 275 * skipping over occurrences of {@link Optional#absent}. Iterators are unmodifiable and are 276 * evaluated lazily. 277 * 278 * <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's 279 * {@code Optional} class; use 280 * {@code optionals.stream().filter(Optional::isPresent).map(Optional::get)} instead. 281 * 282 * @since 11.0 (generics widened in 13.0) 283 */ 284 @Beta 285 public static <T> Iterable<T> presentInstances( 286 final Iterable<? extends Optional<? extends T>> optionals) { 287 checkNotNull(optionals); 288 return new Iterable<T>() { 289 @Override 290 public Iterator<T> iterator() { 291 return new AbstractIterator<T>() { 292 private final Iterator<? extends Optional<? extends T>> iterator = 293 checkNotNull(optionals.iterator()); 294 295 @Override 296 protected T computeNext() { 297 while (iterator.hasNext()) { 298 Optional<? extends T> optional = iterator.next(); 299 if (optional.isPresent()) { 300 return optional.get(); 301 } 302 } 303 return endOfData(); 304 } 305 }; 306 } 307 }; 308 } 309 310 private static final long serialVersionUID = 0; 311}