Cast To Nullable Type

ID

kotlin.cast_to_nullable

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Kotlin

Tags

correctness, null-safety

Description

Reports uses of as Type? where the safe cast as? Type was likely intended.

x as String? does NOT return null when the cast fails — it still throws ClassCastException if x is not a String. The nullable target type is misleading. The correct idiom for a cast that should yield null on a type mismatch is x as? String.

Rationale

// Bad — looks safe but ClassCastException is still possible
val s: String? = obj as String?  // FLAW

// Good — as? returns null when obj is not a String
val s: String? = obj as? String

Remediation

Replace x as Type? with x as? Type. If you also need to suppress null receiver exceptions, combine it with the Elvis operator: x as? Type ?: fallback.