RFR(s): 8140281 add no-arg Optional.orElseThrow() as preferred alternative to get()
Remi Forax
forax at univ-mlv.fr
Fri Dec 8 09:45:35 UTC 2017
Let's gently derail this thread, the is another pain point with the current optional API,
it seems that are no simple way to transform an Optional<Integer> to an OptionalInt and vice-versa.
It's painful because we start to see interface that returns by example OptionalInt while the implementation you want to connect with return an Optional<Integer>.
The only workaround seems to be to use a Stream/IntStream:
Optional -> OptionalInt
optional.stream().mapToInt(x -> x).findFirst()
OptionalInt -> Optional
optionalInt.stream().boxed().findFirst();
I think, Optional should have the method mapTo*/flatMapTo* and Optional[Primitive] the method boxed().
regards,
Rémi
----- Mail original -----
> De: "Stuart Marks" <stuart.marks at oracle.com>
> À: "core-libs-dev" <core-libs-dev at openjdk.java.net>
> Envoyé: Vendredi 8 Décembre 2017 01:33:41
> Objet: RFR(s): 8140281 add no-arg Optional.orElseThrow() as preferred alternative to get()
> Hi all,
>
> Please review this changeset that introduces a new no-arg method orElseThrow()
> to Optional, as a preferred alternative to the get() method.
>
> Corresponding methods are also added to OptionalDouble, Int, and Long.
>
> The orElseThrow() method is functionally identical to get(). It has some
> affinity with the existing orElseThrow(exceptionSupplier) method, being
> equivalent to orElseThrow(NoSuchElementException::new).
>
> The get() method is functionally unchanged. It is NOT being deprecated, although
> some wording in the doc has been added to point to orElseThrow() as the
> "preferred alternative." This is part of a (slow) migration away from
> Optional.get(), which has an obvious, attractive name that is often misused.
> These issues have been discussed on this list previously:
>
> http://mail.openjdk.java.net/pipermail/core-libs-dev/2016-April/040484.html
>
> Please note that much of that discussion was about the then-proposed deprecation
> of Optional.get(), which is NOT part of this proposal. There are no plans to
> deprecate Optional.get() at this time. This proposal ONLY introduces a new
> method orElseThrow() that is identical in function to get().
>
> Bug report:
>
> https://bugs.openjdk.java.net/browse/JDK-8140281
>
> Webrev:
>
> http://cr.openjdk.java.net/~smarks/reviews/8140281/webrev.1/
>
> Thanks,
>
> s'marks
More information about the core-libs-dev
mailing list