Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Idea lint warning about missing `isPresent()` check in `orElseGet`?

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?

like image 977
Blacklight Avatar asked Jun 20 '17 19:06

Blacklight


People also ask

How do I make optional isPresent false?

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.

What exception is thrown by optional get () when not nested within optional isPresent ()?

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.

Can optional GET be null?

A variable whose type is Optional should never itself be null . It should always point to an Optional instance.


1 Answers

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

like image 51
Eugene Avatar answered Sep 21 '22 02:09

Eugene