KT-10005 Java to Kotlin: do not convert type cast to cast to nullable if it should not be null

#KT-10005 Fixed
This commit is contained in:
Valentin Kipyatkov
2015-11-20 15:58:49 +03:00
parent d78390e489
commit f98b354bc1
5 changed files with 38 additions and 2 deletions
@@ -480,12 +480,24 @@ class DefaultExpressionConverter : JavaElementVisitor(), ExpressionConverter {
result = MethodCallExpression.buildNotNull(operandConverted, typeConversion)
}
else {
val typeConverted = typeConverter.convertType(castType.getType(),
if (operandConverted.isNullable) Nullability.Nullable else Nullability.NotNull)
val nullability = if (operandConverted.isNullable && !expression.isQualifier())
Nullability.Nullable
else
Nullability.NotNull
val typeConverted = typeConverter.convertType(castType.type, nullability)
result = TypeCastExpression(typeConverted, operandConverted)
}
}
private fun PsiExpression.isQualifier(): Boolean {
val parent = parent
when (parent) {
is PsiParenthesizedExpression -> return parent.isQualifier()
is PsiReferenceExpression -> return this == parent.qualifierExpression
else -> return false
}
}
override fun visitPolyadicExpression(expression: PsiPolyadicExpression) {
val args = expression.getOperands().map { codeConverter.convertExpression(it, expression.getType()) }
result = PolyadicExpression(args, getOperatorString(expression.getOperationTokenType()))
@@ -0,0 +1,6 @@
public class A {
void foo(Object o) {
if (o == null) return;
int length = ((String) o).length();
}
}
@@ -0,0 +1,6 @@
class A {
internal fun foo(o: Any?) {
if (o == null) return
val length = (o as String).length
}
}
@@ -4318,6 +4318,12 @@ public class JavaToKotlinConverterForWebDemoTestGenerated extends AbstractJavaTo
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("j2k/testData/fileOrElement/typeCastExpression"), Pattern.compile("^(.+)\\.java$"), true);
}
@TestMetadata("beforeDot.java")
public void testBeforeDot() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("j2k/testData/fileOrElement/typeCastExpression/beforeDot.java");
doTest(fileName);
}
@TestMetadata("castNullable.java")
public void testCastNullable() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("j2k/testData/fileOrElement/typeCastExpression/castNullable.java");
@@ -4318,6 +4318,12 @@ public class JavaToKotlinConverterSingleFileTestGenerated extends AbstractJavaTo
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("j2k/testData/fileOrElement/typeCastExpression"), Pattern.compile("^(.+)\\.java$"), true);
}
@TestMetadata("beforeDot.java")
public void testBeforeDot() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("j2k/testData/fileOrElement/typeCastExpression/beforeDot.java");
doTest(fileName);
}
@TestMetadata("castNullable.java")
public void testCastNullable() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("j2k/testData/fileOrElement/typeCastExpression/castNullable.java");