我正在寻找此代码的更优雅的解决方案:
var first = Optional.ofNullable(a);
var second = Optional.ofNullable(b);
if ((unit.isPresent() && value.isEmpty()) || (value.isPresent() &&
unit.isEmpty())) {
throw new ExpWhatever();
}
Run Code Online (Sandbox Code Playgroud)
条件是:
感谢您的任何想法或帮助。
听起来isPresent()对于其中之一正确是一个错误-因此XOR运作良好:
if (unit.isPresent() ^ value.isPresent()) {
// Throw an exception
}
Run Code Online (Sandbox Code Playgroud)
如果您希望两个可选参数都存在或为空(即它们具有相同的“空”状态),则可以使用以下方法:
if (unit.isPresent() != value.isPresent()) {
//throw an exception
}
Run Code Online (Sandbox Code Playgroud)