【问题标题】:Problem about argument of Java 8 OptionalInt.of [duplicate]关于 Java 8 OptionalInt.of [重复] 参数的问题
【发布时间】:2020-02-21 08:54:45
【问题描述】:

1)

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

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

Optional.ofNullable(boxed) 应该返回 Optional&lt;Integer&gt;,而不是 int。

2) 为什么下面的不能编译?

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

【问题讨论】:

  • 您可以在需要int 的地方传递Integer,这称为自动装箱。但是你不能在需要Optional的地方传递OptionalInt,这些不相关的类型之间没有转换。

标签: java optional


【解决方案1】:

1) Optionalmap() 需要一个映射器Function 来返回一个? extends U,所以它可以返回一个OptionalInt。因此它接受OptionalInt::of。由于自动拆箱,您可以将Integer 传递给OptionalInt.of()

2) OptionalflatMap() 需要一个返回 Optional&lt;U&gt; 的映射器 FunctionOptionalInt 不是 Optional,因此您不能将 OptionalInt::of 传递给它。

【讨论】:

  • 对于1,Optional.ofNullable(boxed).map(OptionalInt::of),OptinalInt::of的参数不是Optional?
  • @user1169587 OptionalInt.of() 的参数是int,所以 OptionalInt::of 可以用来实现Function&lt;Integer,OptionalInt&gt;,但不能实现Function&lt;Integer,Optional&lt;Integer&gt;&gt;,这是flatMap 需要的.
  • 好的,我再次检查可选映射api,“如果存在值,则对其应用提供的映射函数”,“it”是值(整数),而不是容器(可选)
猜你喜欢
  • 2013-03-05
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 2010-12-25
  • 2011-09-22
  • 2015-01-03
  • 1970-01-01
相关资源
最近更新 更多