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.
fun numberMagic(number: Number) {
val i = if (number is Int) number else null
// ...
}
Use the safe cast operator (as?
) instead.
fun numberMagic(number: Number) {
val i = number as? Int
// ...
}