mirror of
https://github.com/jlengrand/detekt.git
synced 2026-03-10 08:11:23 +00:00
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:
@@ -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}')" +
|
||||||
|
|||||||
@@ -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()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user