【译】【原文翻译计划】Java Optional的flatMap方法

原文节选自《java 8 in Action》, 297页:

原文如下:
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, 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.

译文:
这里从包装一个Person对象的optional对象开始,对其调用flatMap(Person::getCar)方法。正如我们前面说的,你逻辑上可以认为这个调用包含两步:第一步,一个Function被应用在Optional对象中的Person对象上,其目的是把Person对象转换成一个其他的对象。在这里,这个Function就是用Person对象的getCar方法。由于这个方法返回一个Optional对象,在Optional对象中的Person就会被转换成为Optional对象,结果就是一个两层的Optional对象,这个对象会被打平,成为flatMap操作的一部分。理论上来说,你可以认为这个打平操作是一个把2个Optioanl对象结合在一起的操作,如果其中有一个对象是空的,那就会返回一个Optional.Empty对象。实际上,如果你在一个Empty的Optional对象上做调用flatMap方法,什么都不会改变,一个Empty Optional就会被返回回来。相反的,如果Optional对象包装了一个Person对象,那这个Funtion就会作用在这个Persion对象上。由于Function对象返回的已经是一个Optional对象了,那这个flatMap就直接把这个Optional对象给返回了。

上一篇:解决el-input-number修改值后不更新


下一篇:「工具」Optional处理非空判断