Coverage Summary for Class: Optional (com.google.common.base)

Class Method, % Line, %
Optional 50% (4/8) 44.4% (4/9)
Optional$1 0% (0/2) 0% (0/2)
Optional$1$1 0% (0/2) 0% (0/8)
Total 33.3% (4/12) 21.1% (4/19)


1 /* 2  * Copyright (C) 2011 The Guava Authors 3  * 4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5  * in compliance with the License. You may obtain a copy of the License at 6  * 7  * http://www.apache.org/licenses/LICENSE-2.0 8  * 9  * Unless required by applicable law or agreed to in writing, software distributed under the License 10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11  * or implied. See the License for the specific language governing permissions and limitations under 12  * the License. 13  */ 14  15 package com.google.common.base; 16  17 import static com.google.common.base.Preconditions.checkNotNull; 18  19 import com.google.common.annotations.Beta; 20 import com.google.common.annotations.GwtCompatible; 21 import com.google.errorprone.annotations.DoNotMock; 22 import java.io.Serializable; 23 import java.util.Iterator; 24 import java.util.Set; 25 import javax.annotation.CheckForNull; 26  27 /** 28  * An immutable object that may contain a non-null reference to another object. Each instance of 29  * this type either contains a non-null reference, or contains nothing (in which case we say that 30  * the reference is "absent"); it is never said to "contain {@code null}". 31  * 32  * <p>A non-null {@code Optional<T>} reference can be used as a replacement for a nullable {@code T} 33  * reference. It allows you to represent "a {@code T} that must be present" and a "a {@code T} that 34  * might be absent" as two distinct types in your program, which can aid clarity. 35  * 36  * <p>Some uses of this class include 37  * 38  * <ul> 39  * <li>As a method return type, as an alternative to returning {@code null} to indicate that no 40  * value was available 41  * <li>To distinguish between "unknown" (for example, not present in a map) and "known to have no 42  * value" (present in the map, with value {@code Optional.absent()}) 43  * <li>To wrap nullable references for storage in a collection that does not support {@code null} 44  * (though there are <a 45  * href="https://github.com/google/guava/wiki/LivingWithNullHostileCollections">several other 46  * approaches to this</a> that should be considered first) 47  * </ul> 48  * 49  * <p>A common alternative to using this class is to find or create a suitable <a 50  * href="http://en.wikipedia.org/wiki/Null_Object_pattern">null object</a> for the type in question. 51  * 52  * <p>This class is not intended as a direct analogue of any existing "option" or "maybe" construct 53  * from other programming environments, though it may bear some similarities. 54  * 55  * <p><b>Comparison to {@code java.util.Optional} (JDK 8 and higher):</b> A new {@code Optional} 56  * class was added for Java 8. The two classes are extremely similar, but incompatible (they cannot 57  * share a common supertype). <i>All</i> known differences are listed either here or with the 58  * relevant methods below. 59  * 60  * <ul> 61  * <li>This class is serializable; {@code java.util.Optional} is not. 62  * <li>{@code java.util.Optional} has the additional methods {@code ifPresent}, {@code filter}, 63  * {@code flatMap}, and {@code orElseThrow}. 64  * <li>{@code java.util} offers the primitive-specialized versions {@code OptionalInt}, {@code 65  * OptionalLong} and {@code OptionalDouble}, the use of which is recommended; Guava does not 66  * have these. 67  * </ul> 68  * 69  * <p><b>There are no plans to deprecate this class in the foreseeable future.</b> However, we do 70  * gently recommend that you prefer the new, standard Java class whenever possible. 71  * 72  * <p>See the Guava User Guide article on <a 73  * href="https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained#optional">using {@code 74  * Optional}</a>. 75  * 76  * @param <T> the type of instance that can be contained. {@code Optional} is naturally covariant on 77  * this type, so it is safe to cast an {@code Optional<T>} to {@code Optional<S>} for any 78  * supertype {@code S} of {@code T}. 79  * @author Kurt Alfred Kluever 80  * @author Kevin Bourrillion 81  * @since 10.0 82  */ 83 @DoNotMock("Use Optional.of(value) or Optional.absent()") 84 @GwtCompatible(serializable = true) 85 @ElementTypesAreNonnullByDefault 86 public abstract class Optional<T> implements Serializable { 87  /** 88  * Returns an {@code Optional} instance with no contained reference. 89  * 90  * <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's 91  * {@code Optional.empty}. 92  */ 93  public static <T> Optional<T> absent() { 94  return Absent.withType(); 95  } 96  97  /** 98  * Returns an {@code Optional} instance containing the given non-null reference. To have {@code 99  * null} treated as {@link #absent}, use {@link #fromNullable} instead. 100  * 101  * <p><b>Comparison to {@code java.util.Optional}:</b> no differences. 102  * 103  * @throws NullPointerException if {@code reference} is null 104  */ 105  public static <T> Optional<T> of(T reference) { 106  return new Present<T>(checkNotNull(reference)); 107  } 108  109  /** 110  * If {@code nullableReference} is non-null, returns an {@code Optional} instance containing that 111  * reference; otherwise returns {@link Optional#absent}. 112  * 113  * <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's 114  * {@code Optional.ofNullable}. 115  */ 116  public static <T> Optional<T> fromNullable(@CheckForNull T nullableReference) { 117  return (nullableReference == null) ? Optional.<T>absent() : new Present<T>(nullableReference); 118  } 119  120  /** 121  * Returns the equivalent {@code com.google.common.base.Optional} value to the given {@code 122  * java.util.Optional}, or {@code null} if the argument is null. 123  * 124  * @since 21.0 125  */ 126  @CheckForNull 127  public static <T> Optional<T> fromJavaUtil(@CheckForNull java.util.Optional<T> javaUtilOptional) { 128  return (javaUtilOptional == null) ? null : fromNullable(javaUtilOptional.orElse(null)); 129  } 130  131  /** 132  * Returns the equivalent {@code java.util.Optional} value to the given {@code 133  * com.google.common.base.Optional}, or {@code null} if the argument is null. 134  * 135  * <p>If {@code googleOptional} is known to be non-null, use {@code googleOptional.toJavaUtil()} 136  * instead. 137  * 138  * <p>Unfortunately, the method reference {@code Optional::toJavaUtil} will not work, because it 139  * could refer to either the static or instance version of this method. Write out the lambda 140  * expression {@code o -> Optional.toJavaUtil(o)} instead. 141  * 142  * @since 21.0 143  */ 144  @CheckForNull 145  public static <T> java.util.Optional<T> toJavaUtil(@CheckForNull Optional<T> googleOptional) { 146  return googleOptional == null ? null : googleOptional.toJavaUtil(); 147  } 148  149  /** 150  * Returns the equivalent {@code java.util.Optional} value to this optional. 151  * 152  * <p>Unfortunately, the method reference {@code Optional::toJavaUtil} will not work, because it 153  * could refer to either the static or instance version of this method. Write out the lambda 154  * expression {@code o -> o.toJavaUtil()} instead. 155  * 156  * @since 21.0 157  */ 158  public java.util.Optional<T> toJavaUtil() { 159  return java.util.Optional.ofNullable(orNull()); 160  } 161  162  Optional() {} 163  164  /** 165  * Returns {@code true} if this holder contains a (non-null) instance. 166  * 167  * <p><b>Comparison to {@code java.util.Optional}:</b> no differences. 168  */ 169  public abstract boolean isPresent(); 170  171  /** 172  * Returns the contained instance, which must be present. If the instance might be absent, use 173  * {@link #or(Object)} or {@link #orNull} instead. 174  * 175  * <p><b>Comparison to {@code java.util.Optional}:</b> when the value is absent, this method 176  * throws {@link IllegalStateException}, whereas the Java 8 counterpart throws {@link 177  * java.util.NoSuchElementException NoSuchElementException}. 178  * 179  * @throws IllegalStateException if the instance is absent ({@link #isPresent} returns {@code 180  * false}); depending on this <i>specific</i> exception type (over the more general {@link 181  * RuntimeException}) is discouraged 182  */ 183  public abstract T get(); 184  185  /** 186  * Returns the contained instance if it is present; {@code defaultValue} otherwise. If no default 187  * value should be required because the instance is known to be present, use {@link #get()} 188  * instead. For a default value of {@code null}, use {@link #orNull}. 189  * 190  * <p>Note about generics: The signature {@code public T or(T defaultValue)} is overly 191  * restrictive. However, the ideal signature, {@code public <S super T> S or(S)}, is not legal 192  * Java. As a result, some sensible operations involving subtypes are compile errors: 193  * 194  * <pre>{@code 195  * Optional<Integer> optionalInt = getSomeOptionalInt(); 196  * Number value = optionalInt.or(0.5); // error 197  * 198  * FluentIterable<? extends Number> numbers = getSomeNumbers(); 199  * Optional<? extends Number> first = numbers.first(); 200  * Number value = first.or(0.5); // error 201  * }</pre> 202  * 203  * <p>As a workaround, it is always safe to cast an {@code Optional<? extends T>} to {@code 204  * Optional<T>}. Casting either of the above example {@code Optional} instances to {@code 205  * Optional<Number>} (where {@code Number} is the desired output type) solves the problem: 206  * 207  * <pre>{@code 208  * Optional<Number> optionalInt = (Optional) getSomeOptionalInt(); 209  * Number value = optionalInt.or(0.5); // fine 210  * 211  * FluentIterable<? extends Number> numbers = getSomeNumbers(); 212  * Optional<Number> first = (Optional) numbers.first(); 213  * Number value = first.or(0.5); // fine 214  * }</pre> 215  * 216  * <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's {@code 217  * Optional.orElse}, but will not accept {@code null} as a {@code defaultValue} ({@link #orNull} 218  * must be used instead). As a result, the value returned by this method is guaranteed non-null, 219  * which is not the case for the {@code java.util} equivalent. 220  */ 221  public abstract T or(T defaultValue); 222  223  /** 224  * Returns this {@code Optional} if it has a value present; {@code secondChoice} otherwise. 225  * 226  * <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's 227  * {@code Optional} class; write {@code thisOptional.isPresent() ? thisOptional : secondChoice} 228  * instead. 229  */ 230  public abstract Optional<T> or(Optional<? extends T> secondChoice); 231  232  /** 233  * Returns the contained instance if it is present; {@code supplier.get()} otherwise. 234  * 235  * <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's {@code 236  * Optional.orElseGet}, except when {@code supplier} returns {@code null}. In this case this 237  * method throws an exception, whereas the Java 8 method returns the {@code null} to the caller. 238  * 239  * @throws NullPointerException if this optional's value is absent and the supplier returns {@code 240  * null} 241  */ 242  @Beta 243  public abstract T or(Supplier<? extends T> supplier); 244  245  /** 246  * Returns the contained instance if it is present; {@code null} otherwise. If the instance is 247  * known to be present, use {@link #get()} instead. 248  * 249  * <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's 250  * {@code Optional.orElse(null)}. 251  */ 252  @CheckForNull 253  public abstract T orNull(); 254  255  /** 256  * Returns an immutable singleton {@link Set} whose only element is the contained instance if it 257  * is present; an empty immutable {@link Set} otherwise. 258  * 259  * <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's 260  * {@code Optional} class. However, this common usage: 261  * 262  * <pre>{@code 263  * for (Foo foo : possibleFoo.asSet()) { 264  * doSomethingWith(foo); 265  * } 266  * }</pre> 267  * 268  * ... can be replaced with: 269  * 270  * <pre>{@code 271  * possibleFoo.ifPresent(foo -> doSomethingWith(foo)); 272  * }</pre> 273  * 274  * <p><b>Java 9 users:</b> some use cases can be written with calls to {@code optional.stream()}. 275  * 276  * @since 11.0 277  */ 278  public abstract Set<T> asSet(); 279  280  /** 281  * If the instance is present, it is transformed with the given {@link Function}; otherwise, 282  * {@link Optional#absent} is returned. 283  * 284  * <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's {@code 285  * Optional.map}, except when {@code function} returns {@code null}. In this case this method 286  * throws an exception, whereas the Java 8 method returns {@code Optional.absent()}. 287  * 288  * @throws NullPointerException if the function returns {@code null} 289  * @since 12.0 290  */ 291  public abstract <V> Optional<V> transform(Function<? super T, V> function); 292  293  /** 294  * Returns {@code true} if {@code object} is an {@code Optional} instance, and either the 295  * contained references are {@linkplain Object#equals equal} to each other or both are absent. 296  * Note that {@code Optional} instances of differing parameterized types can be equal. 297  * 298  * <p><b>Comparison to {@code java.util.Optional}:</b> no differences. 299  */ 300  @Override 301  public abstract boolean equals(@CheckForNull Object object); 302  303  /** 304  * Returns a hash code for this instance. 305  * 306  * <p><b>Comparison to {@code java.util.Optional}:</b> this class leaves the specific choice of 307  * hash code unspecified, unlike the Java 8 equivalent. 308  */ 309  @Override 310  public abstract int hashCode(); 311  312  /** 313  * Returns a string representation for this instance. 314  * 315  * <p><b>Comparison to {@code java.util.Optional}:</b> this class leaves the specific string 316  * representation unspecified, unlike the Java 8 equivalent. 317  */ 318  @Override 319  public abstract String toString(); 320  321  /** 322  * Returns the value of each present instance from the supplied {@code optionals}, in order, 323  * skipping over occurrences of {@link Optional#absent}. Iterators are unmodifiable and are 324  * evaluated lazily. 325  * 326  * <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's 327  * {@code Optional} class; use {@code 328  * optionals.stream().filter(Optional::isPresent).map(Optional::get)} instead. 329  * 330  * <p><b>Java 9 users:</b> use {@code optionals.stream().flatMap(Optional::stream)} instead. 331  * 332  * @since 11.0 (generics widened in 13.0) 333  */ 334  @Beta 335  public static <T> Iterable<T> presentInstances( 336  final Iterable<? extends Optional<? extends T>> optionals) { 337  checkNotNull(optionals); 338  return new Iterable<T>() { 339  @Override 340  public Iterator<T> iterator() { 341  return new AbstractIterator<T>() { 342  private final Iterator<? extends Optional<? extends T>> iterator = 343  checkNotNull(optionals.iterator()); 344  345  @Override 346  @CheckForNull 347  protected T computeNext() { 348  while (iterator.hasNext()) { 349  Optional<? extends T> optional = iterator.next(); 350  if (optional.isPresent()) { 351  return optional.get(); 352  } 353  } 354  return endOfData(); 355  } 356  }; 357  } 358  }; 359  } 360  361  private static final long serialVersionUID = 0; 362 }