android
runtime_error
ai_generated
true
java.lang.NullPointerException: null cannot be cast to non-null type kotlin.String
ID: android/kotlin-unsafe-cast-npe
93%Fix Rate
83%Confidence
1Evidence
2023-11-28First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| Kotlin 1.5+ | active | — | — | — |
| Android Studio Arctic Fox+ | active | — | — | — |
Root Cause
Using the 'as' keyword for an unsafe cast where the value is null, causing a NullPointerException at runtime.
generic中文
使用 'as' 关键字进行不安全转换,但值为 null,导致运行时 NullPointerException。
Official Documentation
https://kotlinlang.org/docs/null-safety.html#unsafe-cast-operatorWorkarounds
-
95% success Use safe cast operator 'as?' which returns null instead of throwing exception: val str: String? = obj as? String
Use safe cast operator 'as?' which returns null instead of throwing exception: val str: String? = obj as? String
-
90% success Add explicit null check before casting: if (obj != null) { val str: String = obj as String }
Add explicit null check before casting: if (obj != null) { val str: String = obj as String } -
93% success Use the 'is' operator with smart cast: if (obj is String) { val str: String = obj }
Use the 'is' operator with smart cast: if (obj is String) { val str: String = obj }
中文步骤
使用安全转换运算符 'as?',返回 null 而不是抛出异常:val str: String? = obj as? String
在转换前添加显式空检查:if (obj != null) { val str: String = obj as String }使用 'is' 运算符配合智能转换:if (obj is String) { val str: String = obj }
Dead Ends
Common approaches that don't work:
-
90% fail
This only suppresses compiler warnings; the runtime NPE still occurs.
-
50% fail
Catches the symptom but not the root cause; still throws exception and may hide bugs.
-
60% fail
If the cast target is non-null, it will still fail; must use safe cast or null check.