Assume that I don't know if one Optional
is empty, or if both are present. In the latter case, I always want to prefer a
over b
:
final Optional<String> a = Optional.of("1");
final Optional<String> b = Optional.empty();
if (a.isPresent() || b.isPresent()) {
// prefer a over b
Integer result = a
.map(s -> s + "0")
.map(Integer::parseInt)
.orElseGet(() -> Integer.parseInt(b.get())); // <-- warning for b.get()
System.out.println(result);
}
In my real code, Idea is warning me at this point:
'Optional.get()' without 'isPresent()' check.
Why is that? I am checking priorly if either a
or b
is present. Also, this code works as expected, the output is 10
. If I put b = Optional.of("2")
the output is still 10
because I prefer a
. If I then put a = Optional.empty()
, the output is 2
as expected.
Am I doing something wrong, or is Idea's linter wrong?
If you just want an Optional returning false for isPresent() , you don't need to mock the Optional at all but just create an empty one. Of course this test only tests that the mock object actually returns the stubbed return value, but you get the idea.
NoSuchElementException Exception Via orElseThrow() Since Java 10. Using the Optional. orElseThrow() method represents another elegant alternative to the isPresent()-get() pair. Sometimes, when an Optional value is not present, all you want to do is to throw a java.
A variable whose type is Optional should never itself be null . It should always point to an Optional instance.
It's idea that is confused here, it's internal rules probably suppose the checks to isPresent
in the the same Optional chaining.
This obviously lays outside the Optional
checks itself due to (a.isPresent() || b.isPresent())
; it can't possible tell that there's no way to call orElseGet
on an empty optional b
because of those checks...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With