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?
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...