关于Java 8 OptionalInt.of [duplicate]的参数的问题

问题描述 投票:0回答:2

1)

[OptionalInt::of应该接受参数int,但是为什么以下内容可以编译?

Integer boxed=2;
Optional<OptionalInt> optInt=Optional.ofNullable(boxed).map(OptionalInt::of);

[Optional.ofNullable(boxed)应该返回Optional<Integer>,而不是整数。

2)为什么以下内容无法编译?

Optional.ofNullable(boxed).flatMap(OptionalInt::of);
java optional
2个回答
0
投票

前者的工作是由于自动取消装箱。您首先获得Optional<Integer>,然后在创建OptionalInt时将装箱的图元取消装箱。

并且后者应该是地图,而不是flatMap。

Optional.ofNullable(boxed).map(OptionalInt::of);

0
投票

1] Optionalmap需要返回Function的映射器? extends U,因此允许它返回OptionalInt

2] OptionalflatMap需要返回Function的映射器Optional<U>OptionalInt不是Optional,因此无法将OptionalInt :: of传递给它。

© www.soinside.com 2019 - 2024. All rights reserved.