DerBenniAusA
DerBenniAusA

Reputation: 807

Elegant solution for two Optionals, if one is present the other must not be empty

I look for a more elegant solution of this code:

var first = Optional.ofNullable(a);
var second = Optional.ofNullable(b);
if ((unit.isPresent() && value.isEmpty()) || (value.isPresent() && 
     unit.isEmpty())) {
  throw new ExpWhatever();
}

Conditions are:

Thanks for any ideas or help.

Upvotes: 2

Views: 627

Answers (2)

assylias
assylias

Reputation: 328618

If you want both optionals to be either present or empty (i.e. they have the same "emptiness" state), you could use this:

if (unit.isPresent() != value.isPresent()) {
  //throw an exception
}

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1500665

It sounds like it's an error for isPresent() to be true for exactly one of them - so XOR works well:

if (unit.isPresent() ^ value.isPresent()) {
    // Throw an exception
}

Upvotes: 7

Related Questions