CastToNullableType: allow casting null keyword (#4907)

Fix a false positive for CastToNullableType for casting a literal `null` to a nullable type. This can be necessary when providing null as a function argument where the incoming type is parameterized. In this case using e.g. `null as? String` is less meaningful and generates a compiler warning that the cast cannot succeed.
This commit is contained in:
Dominic Zirbel
2022-06-04 04:25:06 -07:00
committed by GitHub
parent ae7b41b571
commit 4b30c6be87
2 changed files with 12 additions and 0 deletions

View File

@@ -42,6 +42,7 @@ class CastToNullableType(config: Config = Config.empty) : Rule(config) {
val operationReference = expression.operationReference val operationReference = expression.operationReference
if (operationReference.getReferencedNameElementType() != KtTokens.AS_KEYWORD) return if (operationReference.getReferencedNameElementType() != KtTokens.AS_KEYWORD) return
if (expression.left.text == KtTokens.NULL_KEYWORD.value) return
val nullableTypeElement = expression.right?.typeElement as? KtNullableType ?: return val nullableTypeElement = expression.right?.typeElement as? KtNullableType ?: return
val message = "Use the safe cast ('as? ${nullableTypeElement.innerType?.text}')" + val message = "Use the safe cast ('as? ${nullableTypeElement.innerType?.text}')" +

View File

@@ -41,4 +41,15 @@ class CastToNullableTypeSpec {
val findings = subject.compileAndLint(code) val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty() assertThat(findings).isEmpty()
} }
@Test
fun `cast null to nullable type is allowed`() {
val code = """
fun foo(a: Any?) {
val x = null as String?
}
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
} }