Java Reference
In-Depth Information
a method, you can tell whether to expect an optional value. This forces you to actively unwrap an
optional to deal with the absence of a value.
10.3. Patterns for adopting Optional
So far, so good; you've learned how to employ optionals in types to clarify your domain model
and the advantages this offers over representing missing values with null references. But how
can you use them now? What can you do with them, or more specifically how can you actually
use a value wrapped in an optional?
10.3.1. Creating Optional objects
The first step before working with Optional is to learn how to create optional objects! There are
several ways.
Empty optional
As mentioned earlier, you can get hold of an empty optional object using the static factory
method Optional.empty:
Optional<Car> optCar = Optional.empty();
Optional from a non-null value
You can also create an optional from a non-null value with the static factory method Optional.of:
Optional<Car> optCar = Optional.of(car);
If car were null, a NullPointerException would be immediately thrown (rather than getting a
latent error once you try to access properties of the car).
Optional from null
Finally, by using the static factory method Optional.ofNullable, you can create an Optional
object that may hold a null value:
Optional<Car> optCar = Optional.ofNullable(car);
If car were null, the resulting Optional object would be empty.
 
Search WWH ::




Custom Search