From 7f514158cc53f3b93cdffbbda9366dfca962c340 Mon Sep 17 00:00:00 2001 From: Dominic Zirbel Date: Sat, 4 Jun 2022 00:50:50 -0700 Subject: [PATCH] CastToNullableType: allow casting null keyword 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. --- .../detekt/rules/bugs/CastToNullableType.kt | 1 + .../detekt/rules/bugs/CastToNullableTypeSpec.kt | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/detekt-rules-errorprone/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/CastToNullableType.kt b/detekt-rules-errorprone/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/CastToNullableType.kt index 6c8dff9489e..2e9c3231441 100644 --- a/detekt-rules-errorprone/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/CastToNullableType.kt +++ b/detekt-rules-errorprone/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/CastToNullableType.kt @@ -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}')" + diff --git a/detekt-rules-errorprone/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/CastToNullableTypeSpec.kt b/detekt-rules-errorprone/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/CastToNullableTypeSpec.kt index 5c78098ce18..0e8cfde05ae 100644 --- a/detekt-rules-errorprone/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/CastToNullableTypeSpec.kt +++ b/detekt-rules-errorprone/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/CastToNullableTypeSpec.kt @@ -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() + } }