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.
val nullableValue: String? = null
val nonNullableValue: String = nullableValue as String // Unsafe cast!
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