From b1d286f8f6c40248485d991efb80ff978436995f Mon Sep 17 00:00:00 2001 From: Tagir Valeev Date: Mon, 14 Aug 2017 17:47:34 +0700 Subject: [PATCH] IDEA-177515 Optional.isPresent() refactoring should not be suggested for ternary with incompatible branch types --- .../OptionalIsPresentInspection.java | 8 ++++++-- .../optionalIsPresent/beforeTernaryWrongType.java | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/optionalIsPresent/beforeTernaryWrongType.java diff --git a/java/java-impl/src/com/intellij/codeInspection/OptionalIsPresentInspection.java b/java/java-impl/src/com/intellij/codeInspection/OptionalIsPresentInspection.java index 80029a2f88bb..4470656d7122 100644 --- a/java/java-impl/src/com/intellij/codeInspection/OptionalIsPresentInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/OptionalIsPresentInspection.java @@ -368,8 +368,12 @@ public class OptionalIsPresentInspection extends BaseJavaBatchLocalInspectionToo if(!(trueElement instanceof PsiExpression) || !(falseElement instanceof PsiExpression)) return ProblemType.NONE; PsiExpression trueExpression = (PsiExpression)trueElement; PsiExpression falseExpression = (PsiExpression)falseElement; - return (isSimpleOrUnchecked(falseExpression)) ? - getTypeByLambdaCandidate(optionalVariable, trueExpression, falseExpression) : ProblemType.NONE; + PsiType trueType = trueExpression.getType(); + PsiType falseType = falseExpression.getType(); + if (trueType == null || falseType == null || !trueType.isAssignableFrom(falseType) || !isSimpleOrUnchecked(falseExpression)) { + return ProblemType.NONE; + } + return getTypeByLambdaCandidate(optionalVariable, trueExpression, falseExpression); } @Override diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/optionalIsPresent/beforeTernaryWrongType.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/optionalIsPresent/beforeTernaryWrongType.java new file mode 100644 index 000000000000..d2f47f99f10e --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/optionalIsPresent/beforeTernaryWrongType.java @@ -0,0 +1,14 @@ +// "Replace Optional.isPresent() condition with functional style expression" "false" + +import java.time.LocalDate; +import java.util.Optional; + +public class OptionalTest { + Optional date = Optional.of(LocalDate.now()); + + @Override + public String toString() { + final String x = "{date:" + (date.isPresent() ? date.get() : "") + '}'; + return x; + } +}