java - Optional in orElse-Branch throws Exception -
this question has answer here:
- java 8's orelse not working expected 1 answer
so i'm working optionals , came across strange behaviour. want know if intendet "feature" or something...odd...
here given example: i've got method optional in orelse want evaluate other optional. if other optional not present, i'll raise illegalargumentexception:
firstoptionalvar.orelse(secondoptionalvar.orelsethrow(illegalargumentexception::new));
now if secondoptionalvar
empty optional, raise illegalargumentexception, if firstoptionalvar
present. doesn't seem right me. expect raise illegalargumentexception if firstoptionalvar
not present.
it's not big deal arround behavior java7-methods like:
firstoptionalvar.ispresent() ? firstoptionalvar.get() : secondoptionalvar.orelsethrow(illegalargumentexception::new);
has else experienced behaviour before? way optionals should behave?
this intended behavior. orelse
expects argument of type t
(whatever generic type of optional
is. orelsethrow
returns t
, needs evaluated first, in order pass parameter orelse
.
what want orelseget
, takes supplier<t>
. delay execution of orelsethrow
until after firstoptionalvar
has been checked.
so code should this:
firstoptionalvar.orelseget(() -> secondoptionalvar.orelsethrow(illegalargumentexception::new));
that turn orelsethrow
section lambda, , evaluate if it's needed (ie. when firstoptionalvar
doesn't have value get).
Comments
Post a Comment