android runtime_error ai_generated true

java.lang.NullPointerException:null 不能转换为非空类型 kotlin.String

java.lang.NullPointerException: null cannot be cast to non-null type kotlin.String

ID: android/kotlin-unsafe-cast-npe

其他格式: JSON · Markdown 中文 · English
93%修复率
83%置信度
1证据数
2023-11-28首次发现

版本兼容性

版本状态引入弃用备注
Kotlin 1.5+ active
Android Studio Arctic Fox+ active

根因分析

使用 'as' 关键字进行不安全转换,但值为 null,导致运行时 NullPointerException。

English

Using the 'as' keyword for an unsafe cast where the value is null, causing a NullPointerException at runtime.

generic

官方文档

https://kotlinlang.org/docs/null-safety.html#unsafe-cast-operator

解决方案

  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 }

无效尝试

常见但无效的做法:

  1. 90% 失败

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

  2. 50% 失败

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

  3. 60% 失败

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