Kotlin

Kotlin

Made by DeepSource

Checked cast can be replaced with a safe cast KT-E1004

Bug risk
Major

Use the safe cast operator (as?) to perform a fallible cast instead of using a condition to check the type before casting. This can simplify operations by directly converting the value to the desired type. The safe cast operator also evaluates to null if the cast fails, reducing verbosity, enforcing null safety, and avoiding an extra if condition.

It is considered idiomatic Kotlin to use as? to cast expressions.

Bad Practice

fun numberMagic(number: Number) {
    val i = if (number is Int) number else null
    // ...
}

Recommended

Use the safe cast operator (as?) instead.

fun numberMagic(number: Number) {
    val i = number as? Int
    // ...
}