orElse-Branch中的可选项抛出异常 [英] Optional in orElse-Branch throws Exception
问题描述
所以我正在与Optionals合作,遇到一个奇怪的行为。我想知道这是否真的是一个intendet功能或某事...奇怪...
So I'm working with Optionals and came across a strange behaviour. I want to know if this is really an intendet "feature" or something...odd...
这是给定的例子:
我有得到一个方法与可选在其orElse我想评估另一个可选。如果其他可选不存在,我将提出一个IllegalArgumentException:
Here is the given example: I've got a method with an Optional in whose orElse I want to evaluate an other optional. If the other Optional is not present, I'll raise an IllegalArgumentException:
firstOptionalVar.orElse(secondOptionalVar.orElseThrow(IllegalArgumentException::new));
现在如果 secondOptionalVar
是一个空可选,它将引发IllegalArgumentException,即使 firstOptionalVar
存在。这对我来说似乎不对。如果 firstOptionalVar
不存在,我希望它只会引发一个IllegalArgumentException。
Now if the secondOptionalVar
is an empty Optional, it will raise an IllegalArgumentException, even if the firstOptionalVar
is Present. This doesn't seem right to me. I would expect it to just raise an IllegalArgumentException if the firstOptionalVar
would not be present.
这不是一件大事使用java7方法来得到这个行为,例如:
It's not a big deal to get arround this behavior with java7-methods like:
firstOptionalVar.isPresent() ? firstOptionalVar.get() : secondOptionalVar.orElseThrow(IllegalArgumentException::new);
有没有人曾经遇到过这种行为?这是否是可选的行为方式?
Has anyone else experienced this behaviour before? Is this really the way optionals should behave?
推荐答案
这是预期的行为。 orElse
期望类型为 T
的参数(无论可选$的通用类型c $ c>是。
orElseThrow
返回一个 T
,所以需要首先进行评估,以便通过参数为 orElse
。
This is the intended behavior. orElse
expects an argument of type T
(whatever the generic type of the Optional
is. orElseThrow
returns a T
, so it needs to be evaluated first, in order to pass the parameter into orElse
.
您想要的是 orElseGet
,它需要一个 Supplier< T>
,这将延迟执行 orElseThrow
直到 firstOptionalVar
已被检查。
What you want is orElseGet
, which takes a Supplier<T>
. That will delay execution of the orElseThrow
until after firstOptionalVar
has already been checked.
所以你的代码应该如下所示:
So your code should look like this:
firstOptionalVar.orElseGet(() -> secondOptionalVar.orElseThrow(IllegalArgumentException::new));
这将把 orElseThrow
部分变成一个lambda,只有在需要的时候才能对它进行评估(即当 firstOptionalVar
没有值得到)。
That will turn the orElseThrow
section into a lambda, and only evaluate it if it's needed (ie. when firstOptionalVar
doesn't have a value to get).
这篇关于orElse-Branch中的可选项抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!