Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Optional orElse orElseThrow inconsistent [duplicate]

If a is Optional[123] and b is Optional[empty].

a.orElse(b.orElseThrow(() -> new UnexpectedInternalException(
                    "Error")))

Why does it throw?

like image 312
Jor Avatar asked Aug 02 '26 16:08

Jor


2 Answers

orElse() is a method, and before that method is executed, its arguments are evaluated. In this case the evaluation of the argument (b.orElseThrow(() -> new UnexpectedInternalException("Error"))) throws an exception.

like image 97
Eran Avatar answered Aug 04 '26 07:08

Eran


Because parameters are evaluated first. This has nothing to do with Optional...

like image 43
Daniel David Kovacs Avatar answered Aug 04 '26 07:08

Daniel David Kovacs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!