Java Reference
In-Depth Information
Person/Car/Insurance dereferencing chain using optionals
Starting with this Optional<Person>, the Car from the Person, the Insurance from the Car, and
the String containing the insurance company name from the Insurance are dereferenced with a
combination of the map and flatMap methods introduced earlier. Figure 10.5 illustrates this
pipeline of operations.
Figure 10.5. The Person/Car/Insurance dereferencing chain using
optionals
Here you begin with the optional wrapping the Person and invoking flatMap(Person::getCar)on
it. As we said, you can logically think of this invocation as something that happens in two steps.
In step 1, a Function is applied to the Person inside the optional to transform it. In this case, the
Function is expressed with a method reference invoking the method getCar on that Person.
Because that method returns an Optional<Car>, the Person inside the optional is transformed
into an instance of that type, resulting in a two-level optional that's flattened as part of the
flatMap operation. From a theoretical point of view, you can think of this flattening operation as
the operation that combines two optionals, resulting in an empty optional, if at least one of them
is empty. What happens in reality is that if you invoke flatMap on an empty optional, nothing is
changed, and it's returned as is. Conversely, if the optional wraps a Person, the Function passed
to the flatMap method is applied to that Person. Because the value produced by that Function
application is already an optional, the flatMap method can return it as is.
 
Search WWH ::




Custom Search