SimplifyOptionalCallChainsInspection.RewrappingCase: check orElse argument (IDEA-220982)

Also disabled for `orElseGet(() -> null)` as it would require more logic to check the lambda content and we already suggest to replace this with `orElse(null)`

GitOrigin-RevId: ec86f715ef0f78c637447d5379a239016ecfd3b6
This commit is contained in:
Tagir Valeev
2019-08-22 08:03:04 +03:00
committed by intellij-monorepo-bot
parent 2aa816fb81
commit 18fa2bc0f0
4 changed files with 16 additions and 11 deletions
@@ -470,9 +470,12 @@ public class SimplifyOptionalCallChainsInspection extends AbstractBaseJavaLocalI
!EquivalenceChecker.getCanonicalPsiEquivalence().typesAreEquivalent(qualifier.getType(), parentCall.getType())) {
return null;
}
if ("get".equals(call.getMethodExpression().getReferenceName())) {
String name = call.getMethodExpression().getReferenceName();
if ("get".equals(name)) {
SpecialFieldValue fact = CommonDataflow.getExpressionFact(qualifier, DfaFactType.SPECIAL_FIELD_VALUE);
if (DfaFactType.NULLABILITY.fromDfaValue(SpecialField.OPTIONAL_VALUE.extract(fact)) != DfaNullability.NOT_NULL) return null;
} else if ("orElse".equals(name)) {
if (!ExpressionUtils.isNullLiteral(call.getArgumentList().getExpressions()[0])) return null;
}
return new Context(qualifier, parentCall);
}
@@ -490,7 +493,7 @@ public class SimplifyOptionalCallChainsInspection extends AbstractBaseJavaLocalI
if (myType == Type.OptionalGet) {
return OPTIONAL_GET;
}
return OPTIONAL_OR_ELSE_OR_ELSE_GET;
return OPTIONAL_OR_ELSE;
}
private static class Context {
@@ -1,8 +0,0 @@
// "Unwrap" "true"
import java.util.*;
public class Tests {
void test(List<String> list) {
Optional<String> opt = list.stream().filter(Objects::nonNull).findFirst();
}
}
@@ -0,0 +1,8 @@
// "Unwrap" "false"
import java.util.*;
public class Tests {
private Optional<String> test(Optional<String> testOptional, String defaultVal) {
return Optional.ofNullable(testOptional.or<caret>Else(defaultVal));
}
}
@@ -1,8 +1,10 @@
// "Unwrap" "true"
// "Unwrap" "false"
import java.util.*;
public class Tests {
void test(List<String> list) {
// Will be reported as "Excessive lambda usage", changing to orElse which will trigger rewrapping inspection
// no need to do this in single step
Optional<String> opt = Optional.ofNullable(list.stream().filter(Objects::nonNull).findFirst().<caret>orElseGet(() -> null));
}
}