【译】【原文翻译计划】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
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
标签:Function,flatMap,Java,对象,optional,Person,Optional 来源: https://www.cnblogs.com/youyoubaishu/p/15857442.html