【发布时间】:2015-03-17 16:48:45
【问题描述】:
为什么在 OptionalInt 或其他原始可选风格上似乎没有 map()/flatMap() 方法?
stream() 映射操作允许在对象和基元之间进行转换。但是为什么 Optional 不利用这个呢?
OptionalInt profileId = OptionalInt.of(124);
Optional<Profile> profile = profileId.map(i -> getProfile(i)); //no such valid map() method!
【问题讨论】:
-
无论出于何种原因,他们决定不将这些操作包含在 Optional 的原始风格中。
-
但是实现一个将 OptionalInt 转换为 Optional 的方法会阻止什么? Stream 做了类似我想象的事情。
-
也许是为了保持轻量级而忽略了它,因为这是原语的重点?必须有几种 map 和 flatmap 方法的变体来适应其他原始可选风格以及标准对象 Optional。
-
map的返回值是另一种可选的,不是Profile不是吗? -
我不知道原因,但您可以将您的
OptionalInt包裹在Optional中:Profile profile = Optional.of(profileId).filter(OptionalInt::isPresent).map(opt -> getProfile(opt.getAsInt())).orElseThrow(...);。否则使用Optional<Integer>。