0

1)

OptionalInt::of should accept argument int, but why the following can compile?

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

Optional.ofNullable(boxed) should return Optional<Integer>, not int.

2) why the following cannot compile?

Optional.ofNullable(boxed).flatMap(OptionalInt::of);
user1169587
  • 1,104
  • 2
  • 17
  • 34
  • 3
    You can pass an `Integer` where an `int` is required, that’s called autoboxing. But you cannot pass an `OptionalInt` where an `Optional` is required, there is no conversion between these unrelated types. – Holger Feb 21 '20 at 09:00

1 Answers1

1

1) Optional's map() requires a mapper Function that returns a ? extends U, so it is allowed to return an OptionalInt. Therefore it accepts OptionalInt::of. And you can pass an Integer to OptionalInt.of() due to auto-unboxing.

2) Optional's flatMap() requires a mapper Function that returns an Optional<U>. OptionalInt is not an Optional, so you can't pass OptionalInt::of to it.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • for 1, Optional.ofNullable(boxed).map(OptionalInt::of), the argument to OptinalInt::of is not Optional? – user1169587 Feb 21 '20 at 09:22
  • 2
    @user1169587 the argument of `OptionalInt.of()` is `int`, so OptionalInt::of can be used to implement a `Function`, but not a `Function>`, which is what `flatMap` requires. – Eran Feb 21 '20 at 09:25
  • ok, I check the Optional map api again, "If a value is present, apply the provided mapping function to it", the "it" is the value (Integer), not the container (Optional) – user1169587 Feb 21 '20 at 09:47