* 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
* 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.
import static com.google.common.base.Preconditions.checkNotNull;
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
T that might be absent" as two distinct types in your program, which can
Some uses of this class include
nullto indicate that no value was available
null(though there are that should be considered first)
A common alternative to using this class is to find or create a suitablefor 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.
<T> the type of instance that can be contained.
Optionalis naturally covariant on this type, so it is safe to cast an
Optional<S>for any supertype
return (nullableReference == null)
defaultValueotherwise. If no default value should be required because the instance is known to be present, use
get()instead. For a default value of
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:
As a workaround, it is always safe to cast an
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
Optional<? extends T>to
Optional<T>. Casting either of the above example
Numberis 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