OptionalIsPresentInspection: warn if map(x -> nullable).orElse(null)

In this case semantics preserved if map expression returns null.
This commit is contained in:
Tagir Valeev
2017-12-27 15:40:02 +07:00
parent 5e38388822
commit f1bc1f9819
3 changed files with 30 additions and 1 deletions

View File

@@ -186,9 +186,12 @@ public class OptionalIsPresentInspection extends AbstractBaseJavaLocalInspection
if (!hasNoBadRefs) return ProblemType.NONE;
if (!hasOptionalReference.get() || !(lambdaCandidate instanceof PsiExpression)) return ProblemType.INFO;
PsiExpression expression = (PsiExpression)lambdaCandidate;
if (falseExpression != null && NullnessUtil.getExpressionNullness(expression, true) != Nullness.NOT_NULL) {
if (falseExpression != null &&
!ExpressionUtils.isNullLiteral(falseExpression) &&
NullnessUtil.getExpressionNullness(expression, true) != Nullness.NOT_NULL) {
// falseExpression == null is "consumer" case (to be replaced with ifPresent()),
// in this case we don't care about expression nullness
// if falseExpression is null literal, then semantics is preserved
return ProblemType.INFO;
}
return ProblemType.WARNING;

View File

@@ -0,0 +1,13 @@
// "Replace Optional.isPresent() condition with functional style expression" "GENERIC_ERROR_OR_WARNING"
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
public class Main {
public void test(Optional<String> opt, Function<String, Object> onPresent, Supplier<Object> onEmpty) {
// warning level: no semantics change
Object o = opt.map(onPresent::apply).orElse(null);
}
}

View File

@@ -0,0 +1,13 @@
// "Replace Optional.isPresent() condition with functional style expression" "GENERIC_ERROR_OR_WARNING"
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
public class Main {
public void test(Optional<String> opt, Function<String, Object> onPresent, Supplier<Object> onEmpty) {
// warning level: no semantics change
Object o = opt.is<caret>Present() ? onPresent.apply(opt.get()) : null;
}
}