Safe casting

There is also the safe casting operator, as?. This operator checks, before casting, whether or not types are compatible. If they are, then it works as a normal asoperator. If not, a null value is assigned. Notice how in this example, the local variable num has to be declared as a nullable type:

fun safeCasting(any: Any) {
val num: Int? = any as? Int
}

Safe casts can be used with all other null handling operators (safe call, non-null assertions, and Elvis), but Elvis is probably the most useful one. Together they can be used to do a non-null try-cast operation, like this example shows:

fun safeCastingWithElvisl(any: Any) {
val num: Int = any as? Int ?: 0
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.108.22