Java Reference
In-Depth Information
The second step is similar to the first one, transforming the Optional<Car> into an
Optional<Insurance>. Step 3 turns the Optional<Insurance> into an Optional<String>: because
the Insurance.getName() method returns a String, in this case a flatMap isn't necessary.
At this point the resulting optional will be empty if any of the methods in this invocation chain
returns an empty optional or will contain the desired insurance company name otherwise. So
how do you read that value? After all, you'll end up getting an Optional<String> that may or
may not contain the name of the insurance company. In listing 10.5 , we used another method
called orElse, which provides a default value in case the optional is empty. There are many
methods to provide default actions or unwrap an optional. Let's look at them in more detail.
Using optionals in a domain model and why they're not Serializable
In listing 10.4 , we showed how to use Optionals in your domain model in order to mark with a
specific type the values that are allowed to be missing or remain undefined. However, the
designers of the Optional class developed it from different assumptions and with a different use
case in mind. In particular, Java Language Architect Brian Goetz clearly stated the purpose of
Optional is to support the optional-return idiom only.
Because the Optional class wasn't intended for use as a field type, it also doesn't implement the
Serializable interface. For this reason, using Optionals in your domain model could break
applications using tools or frameworks that require a serializable model to work. Nevertheless,
we believe that we showed why using Optionals as a proper type in your domain is a good idea,
especially when you have to traverse a graph of objects that could be, all or in part, potentially
not present. Alternatively, if you need to have a serializable domain model, we suggest you at
least provide a method allowing access also to any possibly missing value as an optional, as in
the following example:
public class Person {
private Car car;
public Optional<Car> getCarAsOptional() {
return Optional.ofNullable(car);
}
}
Search WWH ::




Custom Search