KT.CAST_TO_NULLABLE_TYPE

Cast to nullable types

Disallow to cast to nullable types. There are cases where as String? is misused as safe cast (as? String). So if you want to prevent those cases, turn on this rule.

Noncompliant Code

Copy
fun foo(a: Any?) {
  val x: String? = a as String? // If 'a' is not String, ClassCastException will be thrown.
}

Compliant Code

Copy
fun foo(a: Any?) {
  val x: String? = a as? String
}

The content on this page is adapted from the Detekt Docs. Copyright ©2022 The Detekt Team. All rights reserved. https://detekt.dev/comments.html