Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2011 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.base;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 import java.util.Set;
 
An immutable object that may contain a non-null reference to another object. Each instance of this type either contains a non-null reference, or contains nothing (in which case we say that the reference is "absent"); it is never said to "contain null".

A non-null Optional<T> reference can be used as a replacement for a nullable T reference. It allows you to represent "a T that must be present" and a "a T that might be absent" as two distinct types in your program, which can aid clarity.

Some uses of this class include

  • As a method return type, as an alternative to returning null to indicate that no value was available
  • To distinguish between "unknown" (for example, not present in a map) and "known to have no value" (present in the map, with value Optional.absent())
  • To wrap nullable references for storage in a collection that does not support null (though there are several other approaches to this that should be considered first)

A common alternative to using this class is to find or create a suitable null object for the type in question.

This class is not intended as a direct analogue of any existing "option" or "maybe" construct from other programming environments, though it may bear some similarities.

See the Guava User Guide article on using Optional.

Parameters:
<T> the type of instance that can be contained. Optional is naturally covariant on this type, so it is safe to cast an Optional<T> to Optional<S> for any supertype S of T.
Author(s):
Kurt Alfred Kluever
Kevin Bourrillion
Since:
10.0
 
 @GwtCompatible(serializable = true)
 public abstract class Optional<T> implements Serializable {
  
Returns an Optional instance with no contained reference.
 
   public static <T> Optional<T> absent() {
     return Absent.withType();
   }

  
Returns an Optional instance containing the given non-null reference.
 
   public static <T> Optional<T> of(T reference) {
     return new Present<T>(checkNotNull(reference));
   }

  
If nullableReference is non-null, returns an Optional instance containing that reference; otherwise returns absent().
 
   public static <T> Optional<T> fromNullable(@Nullable T nullableReference) {
     return (nullableReference == null)
         ? Optional.<T>absent()
         : new Present<T>(nullableReference);
   }
 
   Optional() {}

  
Returns true if this holder contains a (non-null) instance.
  public abstract boolean isPresent();

  
Returns the contained instance, which must be present. If the instance might be absent, use or(java.lang.Object) or orNull() instead.

Throws:
java.lang.IllegalStateException if the instance is absent (isPresent() returns false)
  public abstract T get();

  
Returns the contained instance if it is present; defaultValue otherwise. If no default value should be required because the instance is known to be present, use get() instead. For a default value of null, use orNull().

Note about generics: The signature public T or(T defaultValue) is overly restrictive. However, the ideal signature, public <S super T> S or(S), is not legal Java. As a result, some sensible operations involving subtypes are compile errors:

   Optional<Integer> optionalInt = getSomeOptionalInt();
   Number value = optionalInt.or(0.5); // error

   FluentIterable<? extends Number> numbers = getSomeNumbers();
   Optional<? extends Number> first = numbers.first();
   Number value = first.or(0.5); // error

As a workaround, it is always safe to cast an Optional<? extends T> to Optional<T>. Casting either of the above example Optional instances to Optional<Number> (where Number is the desired output type) solves the problem:

   Optional<Number> optionalInt = (Optional) getSomeOptionalInt();
   Number value = optionalInt.or(0.5); // fine

   FluentIterable<? extends Number> numbers = getSomeNumbers();
   Optional<Number> first = (Optional) numbers.first();
   Number value = first.or(0.5); // fine
  public abstract T or(T defaultValue);

  
Returns this Optional if it has a value present; secondChoice otherwise.
  public abstract Optional<T> or(Optional<? extends T> secondChoice);

  
Returns the contained instance if it is present; supplier.get() otherwise. If the supplier returns null, a java.lang.NullPointerException is thrown.

Throws:
java.lang.NullPointerException if the supplier returns null
  @Beta
  public abstract T or(Supplier<? extends T> supplier);

  
Returns the contained instance if it is present; null otherwise. If the instance is known to be present, use get() instead.
  public abstract T orNull();

  
Returns an immutable singleton java.util.Set whose only element is the contained instance if it is present; an empty immutable java.util.Set otherwise.

Since:
11.0
  public abstract Set<T> asSet();

  
If the instance is present, it is transformed with the given Function; otherwise, absent() is returned. If the function returns null, a java.lang.NullPointerException is thrown.

Throws:
java.lang.NullPointerException if the function returns null
Since:
12.0
  public abstract <V> Optional<V> transform(Function<? super T, V> function);

  
Returns true if object is an Optional instance, and either the contained references are equal to each other or both are absent. Note that Optional instances of differing parameterized types can be equal.
  public abstract boolean equals(@Nullable Object object);

  
Returns a hash code for this instance.
  public abstract int hashCode();

  
Returns a string representation for this instance. The form of this string representation is unspecified.
  public abstract String toString();

  
Returns the value of each present instance from the supplied optionals, in order, skipping over occurrences of absent(). Iterators are unmodifiable and are evaluated lazily.

Since:
11.0 (generics widened in 13.0)
  @Beta
  public static <T> Iterable<T> presentInstances(
      final Iterable<? extends Optional<? extends T>> optionals) {
    checkNotNull(optionals);
    return new Iterable<T>() {
      @Override
      public Iterator<T> iterator() {
        return new AbstractIterator<T>() {
          private final Iterator<? extends Optional<? extends T>> iterator =
              checkNotNull(optionals.iterator());
          @Override
          protected T computeNext() {
            while (.hasNext()) {
              Optional<? extends T> optional = .next();
              if (optional.isPresent()) {
                return optional.get();
              }
            }
            return endOfData();
          }
        };
      }
    };
  }
  private static final long serialVersionUID = 0;
New to GrepCode? Check out our FAQ X