Why does Idea lint warn about the lack of `isPresent ()` check in `orElseGet`?

Suppose I do not know if one is Optionalempty or both are present. In the latter case, I always prefer amore 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, the Idea warns me at this point:

'Optional .get ()' without 'isPresent ()' check.

Why? I check this before if aor is present b. In addition, this code works as expected in the output 10. If I put it b = Optional.of("2"), there will be a way out 10, because I prefer a. If I then deliver a = Optional.empty(), the output will be 2as expected.

Am I doing something wrong or is the lie wrong?

+4
4

, , , , isPresent .

, , Optional - (a.isPresent() || b.isPresent()); , orElseGet b - ...

+3

, IDEA , , , , b.isPresent() a.orElseGet(...).

, , IDE -, (), , , , .

Optional, isPresent api . (), .

, :

final Optional<String> a = Optional.of("1");
final Optional<String> b = Optional.empty();

// prefer a over b
Integer result = a
    .map(s -> s + "0")
    .map(Integer::parseInt)
    .orElseGet(() -> b.map(Integer::parseInt).orElse(0));

System.out.println(result);

, , IllegalStateException :

final Optional<String> a = Optional.of("1");
final Optional<String> b = Optional.empty();

// prefer a over b
Integer result = a
    .map(s -> s + "0")
    .map(Integer::parseInt)
    .orElseGet(() -> b.map(Integer::parseInt).orElseThrow(IllegalStateException::new));

System.out.println(result);
+4

: IDEA 2017.3 (. IDEA-174759).

, , b b.get(). , IDEA . , IDEA , , . , , Integer::parseInt null. Optional.map , a. , , :

private static Integer myParseInt(String s) {
    try {
        return Integer.parseInt(s);
    } catch (NumberFormatException e) {
        return null;
    }
}

...

if (a.isPresent() || b.isPresent()) {
    // prefer a over b
    Integer result = a.map(s -> s + "0").map(MyClass::myParseInt)
                      .orElseGet(() -> Integer.parseInt(b.get()));
    System.out.println(result);
}

b , a , .

IDEA. 2017 :

IDEA 2017.3

, , NULL myParseInt.

IDEA 2017.3 . , IDEA, , GitHub .

. IntelliJ IDEA, .

+2

a.isPresent() b.isPresent() . , , "a.isPresent()", b.isPresent() . - || , . b.get "NoSuchElementException".

b.get() , b , b. IDE , ​​ .

- :

if(a.isPresent()){
//logic if a is there
}
else if(b.isPresent){
//logic if a not there and b is there
}
else{
logic if both are not there
}
0

Source: https://habr.com/ru/post/1679747/


All Articles