Java: add cast to single branch of conditional expression when possible (IDEA-358278)

GitOrigin-RevId: 8f3137172d8a1526da2228e3c9ed911f9805c16c
This commit is contained in:
Bas Leijdekkers
2024-08-26 18:38:16 +00:00
committed by intellij-monorepo-bot
parent 83bba063e7
commit 18cb209fa7
3 changed files with 17 additions and 5 deletions
@@ -93,11 +93,9 @@ public class AddTypeCastFix extends PsiUpdateModCommandAction<PsiExpression> {
PsiConditionalExpression conditional = (PsiConditionalExpression)expression.copy();
PsiExpression thenE = conditional.getThenExpression();
PsiExpression elseE = conditional.getElseExpression();
PsiType thenType = thenE == null ? null : thenE.getType();
PsiType elseType = elseE == null ? null : elseE.getType();
if (elseType != null && thenType != null) {
boolean replaceThen = !TypeConversionUtil.isAssignable(type, thenType);
boolean replaceElse = !TypeConversionUtil.isAssignable(type, elseType);
if (thenE != null && elseE != null) {
boolean replaceThen = !TypeConversionUtil.areTypesAssignmentCompatible(type, thenE);
boolean replaceElse = !TypeConversionUtil.areTypesAssignmentCompatible(type, elseE);
if (replaceThen != replaceElse) {
if (replaceThen) {
Objects.requireNonNull(typeCast.getOperand()).replace(thenE);
@@ -0,0 +1,7 @@
// "Cast expression to 'byte'" "true-preview"
class A {
void f(boolean v) {
int i = 10;
Byte b = v ? 100 : (byte) i;
}
}
@@ -0,0 +1,7 @@
// "Cast expression to 'byte'" "true-preview"
class A {
void f(boolean v) {
int i = 10;
Byte b = <caret> v ? 100 : i;
}
}