Kotlin

Kotlin

Made by DeepSource

Avoid casting to nullable types using as KT-E1002

Bug risk
Major

Avoid casting using as to a nullable type, as it is unsafe and may be misused as a safe cast (as? String).

Casting using as to a nullable type in Kotlin can lead to potential null pointer exceptions if the cast is not successful. This is because the as operator assumes that the cast will always succeed, and throws an exception if it doesn't.

To avoid this, it is recommended to use the safe cast operator (as?) instead, which returns null if the cast is not successful.

Bad Practice

fun foo() {
    val s = 4
    val y: String? = s as String?
}

In the above example, the variable s is casted to String? using the as operator. This is unsafe because if s is not actually a String, a ClassCastException will be thrown.

Recommended

Use the safe cast operator (as?) instead.

fun foo() {
    val s = 4
    val y: String? = s as? String
}