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— throwsClassCastExceptionimmediately if the cast fails -
as?— returnsnullif 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.