Skip to content

Commit

Permalink
CastToNullableType: allow casting null keyword (#4907)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
dzirbel committed Jun 4, 2022
1 parent ae7b41b commit 4b30c6b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
Expand Up @@ -42,6 +42,7 @@ class CastToNullableType(config: Config = Config.empty) : Rule(config) {

val operationReference = expression.operationReference
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 message = "Use the safe cast ('as? ${nullableTypeElement.innerType?.text}')" +
Expand Down
Expand Up @@ -41,4 +41,15 @@ class CastToNullableTypeSpec {
val findings = subject.compileAndLint(code)
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()
}
}

0 comments on commit 4b30c6b

Please sign in to comment.