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

- **ID:** `android/kotlin-unsafe-cast-npe`
- **领域:** android
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 93%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Kotlin 1.5+ | active | — | — |
| Android Studio Arctic Fox+ | active | — | — |

## 解决方案

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 }
   ```

## 无效尝试

- **** — This only suppresses compiler warnings; the runtime NPE still occurs. (90% 失败率)
- **** — Catches the symptom but not the root cause; still throws exception and may hide bugs. (50% 失败率)
- **** — If the cast target is non-null, it will still fail; must use safe cast or null check. (60% 失败率)
