为什么Optional.map使此分配有效? [英] Why does Optional.map make this assignment work?

查看:155
本文介绍了为什么Optional.map使此分配有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Optional<ArrayList<String>> option = Optional.of(new ArrayList<>());

Optional<ArrayList<?>> doesntWork = option;

Optional<ArrayList<?>> works = option.map(list -> list);

第一个尝试的赋值不会编译,但是第二个带有map的赋值会编译.感觉map实际上不应该做任何事情,但是由于某种原因,它使我的Optional<ArrayList<String>>变成了Optional<ArrayList<?>>.是否存在某种隐式强制转换?

The first attempted assignment does not compile, but the second one with the map does. It feels like the map shouldn't actually accomplish anything, but for some reason it turns my Optional<ArrayList<String>> into an Optional<ArrayList<?>>. Is there some sort of implicit cast going on?

推荐答案

如果查看map的代码并遵循所有方法调用,您将看到option.map(list -> list)最终返回new Optional<>(option.get()).因此,您可以将您的上一个作业替换为:

If you look into the code of map and follow all the method calls, you'll see that option.map(list -> list) ends up returning new Optional<>(option.get()). So you can replace your last assignment with:

Optional<ArrayList<?>> works = new Optional<>(option.get());

这将创建一个新的Optional<ArrayList<?>>,并使用map.get()返回的ArrayList<String>初始化其value实例变量(其类型为ArrayList<?>).这是有效的分配.

This creates a new Optional<ArrayList<?>> and initializes its value instance variable (whose type is ArrayList<?>) with the ArrayList<String> returned by map.get(). This is a valid assignment.

是否存在某种隐式强制转换?

Is there some sort of implicit cast going on?

否,map返回一个新的Optional实例.它不会转换调用它的原始实例.

No, map returns a new Optional instance. It doesn't cast the original instance on which it was called.

这是方法调用的链:

option.map(list -> list)

返回(因为option不为空)

Optional.ofNullable(mapper.apply(value))

与您的情况相同

Optional.ofNullable(value)

返回(因为该值不为空):

which returns (since the value is not null):

Optional.of(value)

返回

new Optional<>(value)

这篇关于为什么Optional.map使此分配有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆