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

Also available as: JSON · Markdown · 中文
93%Fix Rate
83%Confidence
1Evidence
2023-11-28First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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-operator

Workarounds

  1. 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
  2. 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 }
  3. 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 }

中文步骤

  1. 使用安全转换运算符 'as?',返回 null 而不是抛出异常:val str: String? = obj as? String
  2. 在转换前添加显式空检查:if (obj != null) { val str: String = obj as String }
  3. 使用 'is' 运算符配合智能转换:if (obj is String) { val str: String = obj }

Dead Ends

Common approaches that don't work:

  1. 90% fail

    This only suppresses compiler warnings; the runtime NPE still occurs.

  2. 50% fail

    Catches the symptom but not the root cause; still throws exception and may hide bugs.

  3. 60% fail

    If the cast target is non-null, it will still fail; must use safe cast or null check.