Cast Nullable To NonNullable
ID |
kotlin.cast_nullable_nonnull |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Kotlin |
Tags |
correctness, null-safety |
Description
Reports casts of a nullable-typed expression to a non-null type using the unsafe as operator,
which throws NullPointerException if the value is null at runtime, bypassing Kotlin’s
null-safety system.
Rationale
fun process(x: String?) {
// Bad — throws NPE if x is null; defeats Kotlin null safety
val s = x as String // FLAW
// Good — as? integrates with the null-safety type system
val s = x as? String ?: return
}
Remediation
Replace x as Type with x as? Type and handle the potential null via the Elvis operator
(?:) or a null check. If a null source should be a programming error, use x!! with a
descriptive error message rather than a silent cast.