Unsafe Cast

ID

kotlin.unsafe_cast

Severity

high

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Kotlin

Tags

null-safety, reliability

Description

Reports uses of the unsafe cast operator (as) that throw ClassCastException at runtime if the object is not of the target type.

Rationale

Kotlin provides two cast operators:

  • as — throws ClassCastException immediately if the cast fails

  • as? — returns null if the cast fails; integrates with Kotlin’s null-safety system

The safe form is almost always preferable. When the result is null, the compiler forces the caller to handle it (via ?., ?:, or a null check), which prevents an unchecked ClassCastException from propagating up the call stack.

// Bad
val s: String = obj as String       // ClassCastException if obj is not String

// Good
val s: String? = obj as? String     // null if obj is not String
val text = (obj as? String) ?: ""   // with a safe fallback

The only legitimate use of as is when the code has already verified the type (e.g., after is smart-cast) and the cast is genuinely unreachable on failure. Even then, prefer as? with an assertion or explicit error over a bare as.

Remediation

Replace expr as T with expr as? T and handle the resulting nullable value. If the cast should never fail, add an explicit check: (expr as? T) ?: error("Expected T but got ${expr?.javaClass}").