IDEA-169678 "Replace Optional.isPresent() condition with functional style expression" breaks code in case of 'Collection' return type

This commit is contained in:
Tagir Valeev
2017-03-16 11:22:15 +07:00
parent b550406e5d
commit 55466aeef1
3 changed files with 48 additions and 2 deletions
@@ -136,7 +136,7 @@ public class OptionalUtil {
}
trueExpression =
targetType == null ? trueExpression : RefactoringUtil.convertInitializerToNormalExpression(trueExpression, targetType);
String typeArg = getMapTypeArgument(trueExpression, targetType);
String typeArg = getMapTypeArgument(trueExpression, targetType, falseExpression);
qualifier += "." + typeArg + "map(" + LambdaUtil.createLambda(var, trueExpression) + ")";
}
if (useOrElseGet && !ExpressionUtils.isSimpleExpression(falseExpression)) {
@@ -154,6 +154,11 @@ public class OptionalUtil {
@NotNull
public static String getMapTypeArgument(PsiExpression expression, PsiType type) {
return getMapTypeArgument(expression, type, null);
}
@NotNull
private static String getMapTypeArgument(PsiExpression expression, PsiType type, PsiExpression falseExpression) {
if (!(type instanceof PsiClassType)) return "";
PsiExpression copy =
JavaPsiFacade.getElementFactory(expression.getProject()).createExpressionFromText(expression.getText(), expression);
@@ -162,7 +167,9 @@ public class OptionalUtil {
!exprType.equals(PsiType.NULL) &&
!LambdaUtil.notInferredType(exprType) &&
TypeConversionUtil.isAssignable(type, exprType)) {
return "";
if (falseExpression == null) return "";
PsiType falseType = falseExpression.getType();
if (falseType != null && falseType.isAssignableFrom(exprType)) return "";
}
return "<" + type.getCanonicalText() + ">";
}
@@ -0,0 +1,18 @@
// "Replace Optional.isPresent() condition with functional style expression" "true"
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
public class TestFile {
public static Collection<String> example() {
final Optional<String> root = Optional.empty();
return root.<Collection<String>>map(TestFile::foo).orElseGet(Collections::emptyList);
}
private static Set<String> foo(String s) {
return Collections.emptySet();
}
}
@@ -0,0 +1,21 @@
// "Replace Optional.isPresent() condition with functional style expression" "true"
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
public class TestFile {
public static Collection<String> example() {
final Optional<String> root = Optional.empty();
if (root<caret>.isPresent()) {
return foo(root.get());
}
return Collections.emptyList();
}
private static Set<String> foo(String s) {
return Collections.emptySet();
}
}