Kotlin

Kotlin

Made by DeepSource

Avoid casting nullable types to non-null types KT-E1006

Bug risk
Major

Casting a nullable type to a non-nullable type in Kotlin can be dangerous and lead to runtime exceptions if the underlying value is null, since while nullable types explicitly allow for null values, non-nullable types disallow null.

Casting a null value to a non-null type will trigger a NullPointerException at runtime. While it is possible that a nullable value may never actually be null, there is no easy way for the compiler or your IDE to know that at compile time.

Additionally, there may not even be a reason to cast to a non-null type explicitly.

Due to Kotlin's smart casting behavior, when code checks the type of a value, or whether the value is null, the compiler will automatically make assumptions relevant to the specific check.

For example, with a check like if (someVal == null), someVal will automatically be assumed to be non-null by the compiler when it executes the check's true branch. Consider using such methods instead of explicitly casting to a non-null type.

Bad Practice

val nullableValue: String? = null
val nonNullableValue: String = nullableValue as String // Unsafe cast!

Recommended

To avoid potential crashes due to NullPointerException, prefer safe casting alternatives.

val nullableValue: String? = null
val nonNullableValue: String? = nullableValue as? String // Safe cast, nonNullableValue will be null