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

- **ID:** `android/kotlin-unsafe-cast-npe`
- **Domain:** android
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 93%

## Root Cause

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

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| Kotlin 1.5+ | active | — | — |
| Android Studio Arctic Fox+ | active | — | — |

## Workarounds

1. **Use safe cast operator 'as?' which returns null instead of throwing exception: val str: String? = obj as? String** (95% success)
   ```
   Use safe cast operator 'as?' which returns null instead of throwing exception: val str: String? = obj as? String
   ```
2. **Add explicit null check before casting: if (obj != null) { val str: String = obj as String }** (90% success)
   ```
   Add explicit null check before casting: if (obj != null) { val str: String = obj as String }
   ```
3. **Use the 'is' operator with smart cast: if (obj is String) { val str: String = obj }** (93% success)
   ```
   Use the 'is' operator with smart cast: if (obj is String) { val str: String = obj }
   ```

## Dead Ends

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